Visi būtiskākie React.js jēdzieni, kas iestrēguši šajā vienā rakstā

Atjauninājums: Šis raksts tagad ir daļa no manas grāmatas “React.js Beyond The Basics”. Izlasiet šī satura atjaunināto versiju un vairāk par React vietnē jscomplete.com/react-beyond-basics .

Šis raksts neattiecas uz to, kas ir React vai kāpēc jums tas būtu jāapgūst. Tā vietā tas ir praktisks ievads React.js pamatos tiem, kas jau pārzina JavaScript un zina DOM API pamatus.

Visi tālāk minētie kodu piemēri ir apzīmēti kā atsauce. To mērķis ir tikai sniegt jēdzienu piemērus. Lielāko daļu no tiem var uzrakstīt daudz labākā veidā.

Fundamentāls # 1: React ir viss par komponentiem

React ir izstrādāts, balstoties uz atkārtoti izmantojamu komponentu koncepciju. Jūs definējat mazus komponentus un saliekat tos kopā, lai izveidotu lielākas sastāvdaļas.

Visas mazās vai lielās sastāvdaļas ir atkārtoti izmantojamas pat dažādos projektos.

React komponents visvienkāršākajā formā ir vienkārša vecā 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)

Cirtainās lencītes, kas tiek izmantotas pogas etiķetei, ir paskaidrotas turpmāk. Neuztraucieties par viņiem tagad. ReactDOMtiks paskaidrots arī vēlāk, bet, ja vēlaties pārbaudīt šo piemēru un visus gaidāmos kodu piemērus, renderjums ir nepieciešama iepriekš minētā funkcija.

Otrais arguments ReactDOM.renderir galamērķa DOM elements, kuru React pārņems un kontrolēs. JsComplete React Playground varat vienkārši izmantot īpašo mainīgo mountNode.

JavaScript REPL un Playground for React.js

Pārbaudiet mūsdienu JavaScript un React.js kodu pārlūkprogrammā bez konfigurācijām jscomplete.com/react

Par 1. piemēru ņemiet vērā šo:

  • Komponenta nosaukums sākas ar lielo burtu. Tas ir nepieciešams, jo mums būs darīšana ar HTML elementu un React elementu kombināciju. HTML elementiem ir rezervēti mazie burti. Patiesībā dodieties uz priekšu un mēģiniet React komponentam nosaukt tikai pogu un uzziniet, kā ReactDOM ignorēs šo funkciju un renderēs parastu tukšu HTML pogu.
  • Katrs komponents saņem atribūtu sarakstu, tāpat kā HTML elementi. In React šo sarakstu sauc par rekvizītiem . Izmantojot funkciju komponentu, jūs to varat nosaukt jebko.
  • Mēs savādi uzrakstījām to, kas izskatās kā HTML, iepriekš norādītās Buttonfunkcijas komponentes atgrieztajā izvadē . Tas nav nedz JavaScript, nedz HTML, un tas pat nav React.js. Bet tas ir tik populārs, ka kļuva par noklusējumu React lietojumprogrammās. To sauc par JSX un tas ir JavaScript paplašinājums. Arī JSX ir kompromiss ! Dodieties uz priekšu un mēģiniet atgriezt jebkuru citu HTML elementu iepriekšējās funkcijas iekšpusē un noskaidrojiet, kā tie visi tiek atbalstīti (piemēram, atgrieziet teksta ievades elementu).

Fundamentāls # 2: kāda ir JSX plūsma?

Iepriekš minēto 1. piemēru var rakstīt tīrā React.js bez JSX šādi:

// 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 ir galvenā funkcija reaģējošā augstākā līmeņa API. Tā ir 1 no kopumā 8 lietām šajā līmenī, kas jums jāapgūst. Tik maza ir React API.

Līdzīgi kā pašam DOM ir document.createElementfunkcija izveidot taga nosaukumā norādītu elementu, arī React createElementfunkcija ir augstāka līmeņa funkcija, kas var darīt to, ko document.createElementdara, bet to var izmantot arī, lai izveidotu elementu, kas pārstāv React komponentu. Mēs izmantojām pēdējo, kad mēs izmantojām iepriekš Button2. piemērā esošo komponentu.

Atšķirībā no tā document.createElement, React's createElementpieņem dinamisku argumentu skaitu pēc otrā, lai pārstāvētu izveidotā elementa bērnus . Tātad createElementfaktiski izveido koku .

Lūk, piemērs tam:

// 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);

Ievērojiet dažas lietas par iepriekš minēto piemēru:

  • InputFormnav React sastāvdaļa; tas ir tikai React elements . Tāpēc mēs to izmantojām tieši ReactDOM.rendersarunā, nevis ar />.
  • 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