Svi temeljni koncepti React.js, zaglavljeni u ovom jednom članku

Ažuriranje: Ovaj je članak sada dio moje knjige "React.js izvan osnova". Pročitajte ažuriranu verziju ovog sadržaja i više o Reactu na jscomplete.com/react-beyond-basics .

Ovaj članak neće pokriti što je React niti zašto biste ga trebali naučiti. Umjesto toga, ovo je praktični uvod u osnove React.js-a za one koji su već upoznati s JavaScriptom i znaju osnove DOM API-ja.

Svi primjeri koda u nastavku označeni su za referencu. Oni su isključivo namijenjeni pružanju primjera koncepata. Većina ih se može napisati na puno bolji način.

Temeljni # 1: React se odnosi na komponente

React je dizajniran oko koncepta komponenata za višekratnu upotrebu. Definirate male komponente i sastavljate ih tako da tvore veće komponente.

Sve male ili velike komponente mogu se ponovno koristiti, čak i u različitim projektima.

Komponenta React - u svom najjednostavnijem obliku - obična je stara JavaScript funkcija:

// Example 1 // //jscomplete.com/repl?j=Sy3QAdKHW function Button (props) { // Returns a DOM element here. For example: return {props.label}; } // To render the Button component to the browser ReactDOM.render(, mountNode)

Kovrčave zagrade korištene za naljepnicu gumba objašnjene su u nastavku. Ne brini sada za njih. ReactDOMtakođer će biti objašnjeno kasnije, ali ako želite testirati ovaj primjer i sve predstojeće primjere koda, gornja renderfunkcija je ono što vam treba.

Drugi argument ReactDOM.renderje odredišni DOM element koji će React preuzeti i kontrolirati. U igralištu jsComplete React možete samo koristiti posebnu varijablu mountNode.

JavaScript REPL i igralište za React.js

Testirajte moderni JavaScript i React.js kôd u pregledniku bez ikakvih konfiguracija jscomplete.com/react

O primjeru 1 imajte na umu sljedeće:

  • Naziv komponente započinje velikim slovom. To je potrebno jer ćemo imati posla s kombinacijom HTML elemenata i React elemenata. Mala slova rezervirana su za HTML elemente. U stvari, samo naprijed i pokušajte nazvati komponentu React samo "gumb" i pogledajte kako će ReactDOM zanemariti funkciju i generira uobičajeni prazan HTML gumb.
  • Svaka komponenta prima popis atributa, baš kao i HTML elementi. U Reactu se ovaj popis naziva rekviziti . S komponentom funkcije možete joj dodijeliti bilo što.
  • Čudno smo napisali kako izgleda HTML u vraćenom izlazu Buttongornje komponente funkcije. Ovo nije ni JavaScript ni HTML, a nije čak ni React.js. Ali, toliko je popularan da je postao zadani u React aplikacijama. Zove se JSX i to je JavaScript proširenje. JSX je također kompromis ! Samo naprijed i pokušajte vratiti bilo koji drugi HTML element unutar gornje funkcije i pogledajte kako su svi podržani (na primjer, vratite element za unos teksta).

Osnovno # 2: Koji je tok JSX?

Primjer 1 gore može se napisati u čistom React.js-u bez JSX-a kako slijedi:

// Example 2 - React component without JSX // //jscomplete.com/repl?j=HyiEwoYB- function Button (props) { return React.createElement( "button", { type: "submit" }, props.label ); } // To use Button, you would do something like ReactDOM.render( React.createElement(Button, { label: "Save" }), mountNode );

createElementFunkcija je glavna funkcija u Reagirati najviše razine API-ja. To je 1 od ukupno 8 stvari na toj razini koje trebate naučiti. Toliko je malen React API.

Slično kao i sam DOM koji ima document.createElementfunkciju za stvaranje elementa navedenog imenom oznake, Reactova createElementfunkcija je funkcija više razine koja može raditi ono što document.createElementmože, ali se također može koristiti za stvaranje elementa koji predstavlja React komponentu. Potonje smo učinili kad smo upotrijebili Buttonkomponentu u gornjem primjeru 2.

Za razliku od toga document.createElement, React's createElementprihvaća dinamički broj argumenata nakon drugog da bi predstavio djecu stvorenog elementa. Tako createElementzapravo stvara drvo .

Evo primjera toga:

// Example 3 - React’s createElement API // //jscomplete.com/repl?j=r1GNoiFBb const InputForm = React.createElement( "form", { target: "_blank", action: "//google.com/search" }, React.createElement("div", null, "Enter input and click Search"), React.createElement("input", { name: "q", className: "input" }), React.createElement(Button, { label: "Search" }) ); // InputForm uses the Button component, so we need that too: function Button (props) { return React.createElement( "button", { type: "submit" }, props.label ); } // Then we can use InputForm directly with .render ReactDOM.render(InputForm, mountNode);

Primijetite nekoliko stvari o gornjem primjeru:

  • InputFormnije React komponenta; to je samo React element . Zbog toga smo ga koristili izravno u ReactDOM.renderpozivu, a ne s njim />.
  • The React.createElement function accepted multiple arguments after the first two. Its list of arguments starting from the 3rd one comprises the list of children for the created element.
  • We were able to nest React.createElement calls because it’s all JavaScript.
  • The second argument to React.createElement can be null or an empty object when no attributes or props are needed for the element.
  • We can mix HTML element with React elements.
  • React’s API tries to be as close to the DOM API as possible, that’s why we use className instead of class for the input element. Secretly, we all wish the React’s API would become part of the DOM API itself. Because, you know, it’s much much better.

The code above is what the browser understands when you include the React library. The browser does not deal with any JSX business. However, we humans like to see and work with HTML instead of these createElement calls (imagine building a website with just document.createElement, which you can!). This is why the JSX compromise exists. Instead of writing the form above with React.createElement calls, we can write it with a syntax very similar to HTML:

// Example 4 - JSX (compare with Example 3) // //jscomplete.com/repl?j=SJWy3otHW const InputForm = Enter input and click Search ; // InputForm "still" uses the Button component, so we need that too. // Either JSX or normal form would do function Button (props) { // Returns a DOM element here. For example: return {props.label}; } // Then we can use InputForm directly with .render ReactDOM.render(InputForm, mountNode);

Note a few things about the above:

  • It’s not HTML. For example, we’re still doing className instead of class.
  • We’re still considering what looks like HTML above as JavaScript. See how I added a semicolon at the end.

What we wrote above (Example 4) is JSX. Yet, what we took to the browser is the compiled version of it (Example 3). To make that happen, we need to use a pre-processor to convert the JSX version into the React.createElement version.

That is JSX. It’s a compromise that allows us to write our React components in a syntax similar to HTML, which is a pretty good deal.

The word “Flux” in the header above was chosen to rhyme, but it’s also the name of a very popular application architecture popularized by Facebook. The most famous implementation of which is Redux. Flux fits the React reactive pattern perfectly.

JSX, by the way, can be used on its own. It’s not a React-only thing.

Fundamental #3: You can use JavaScript expressions anywhere in JSX

Inside a JSX section, you can use any JavaScript expression within a pair of curly braces.

// To use it:ReactDOM.render(, mountNode);// Example 5 - Using JavaScript expressions in JSX // //jscomplete.com/repl?j=SkNN3oYSW const RandomValue = () => { Math.floor(Math.random() * 100) } ; // To use it: ReactDOM.render(, mountNode);

Any JavaScript expression can go inside those curly braces. This is equivalent to the ${} interpolation syntax in JavaScript template literals.

This is the only constraint inside JSX: only expressions. So, for example, you can’t use a regular if statement, but a ternary expression is ok.

JavaScript variables are also expressions, so when the component receives a list of props (the RandomValue component didn’t, props are optional), you can use these props inside curly braces. We did this in the Button component above (Example 1).

JavaScript objects are also expressions. Sometimes we use a JavaScript object inside curly braces, which makes it look like double curly braces, but it’s really just an object inside curly braces. One use case of that is to pass a CSS style object to the special style attribute in React:

// Example 6 - An object passed to the special React style prop // //jscomplete.com/repl?j=S1Kw2sFHb const ErrorDisplay = ({message}) => {message} ; // Use it: ReactDOM.render( , mountNode );

Note how I destructured only the message out of the props argument. Also note how the style attribute above is a special one (again, it’s not HTML, it’s closer to the DOM API). We use an object as the value of the style attribute. That object defines the styles as if we’re doing so with JavaScript (because we are).

You can even use a React element inside JSX, because that too is an expression. Remember, a React element is essentially a function call:

// Example 7 - Using a React element within {} // //jscomplete.com/repl?j=SkTLpjYr- const MaybeError = ({errorMessage}) => {errorMessage && } ; // The MaybeError component uses the ErrorDisplay component: const ErrorDisplay = ({message}) => {message} ; // Now we can use the MaybeError component: ReactDOM.render(  0.5 ? 'Not good' : ''} />, mountNode );

The MaybeError component above would only display the ErrorDisplay component if there is an errorMessage string passed to it and an empty div. React considers {true}, {false}, {undefined}, and {null} to be valid element children, which do not render anything.

You can also use all of JavaScript functional methods on collections (map, reduce, filter, concat, and so on) inside JSX. Again, because they return expressions:

// Example 8 - Using an array map inside {} // //jscomplete.com/repl?j=SJ29aiYH- const Doubler = ({value=[1, 2, 3]}) => {value.map(e => e * 2)} ; // Use it ReactDOM.render(, mountNode);

Note how I gave the value prop a default value above, because it’s all just Javascript. Note also that I outputted an array expression inside the div. React is okay with that; It will place every doubled value in a text node.

Fundamental #4: You can write React components with JavaScript classes

Simple function components are great for simple needs, but sometimes we need more. React supports creating components through the JavaScript class syntax as well. Here’s the Button component (in Example 1) written with the class syntax:

// Example 9 - Creating components using JavaScript classes // //jscomplete.com/repl?j=ryjk0iKHb class Button extends React.Component { render() { return {this.props.label}; } } // Use it (same syntax) ReactDOM.render(, mountNode);

The class syntax is simple. Define a class that extends React.Component (another top-level React API thing that you need to learn). The class defines a single instance function render(), and that render function returns the virtual DOM element. Every time we use the Button class-based component above (for example, by doing