Alle de grundlæggende React.js-koncepter, fastklemt i denne ene artikel

Opdatering: Denne artikel er nu en del af min bog "React.js Beyond The Basics". Læs den opdaterede version af dette indhold og mere om React på jscomplete.com/react-beyond-basics .

Denne artikel dækker ikke hvad React er, eller hvorfor du skal lære det. I stedet er dette en praktisk introduktion til det grundlæggende i React.js for dem, der allerede er fortrolige med JavaScript og kender det grundlæggende i DOM API.

Alle kodeeksempler nedenfor er mærket til reference. De er udelukkende beregnet til at give eksempler på begreber. De fleste af dem kan skrives på en meget bedre måde.

Grundlæggende nr. 1: React handler om komponenter

React er designet omkring konceptet med genanvendelige komponenter. Du definerer små komponenter, og du sætter dem sammen for at danne større komponenter.

Alle små eller store komponenter kan genbruges, selv på tværs af forskellige projekter.

En React-komponent - i sin enkleste form - er en almindelig JavaScript-funktion:

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

De krøllede seler, der bruges til knapmærket, forklares nedenfor. Du skal ikke bekymre dig om dem nu. ReactDOMvil også blive forklaret senere, men hvis du vil teste dette eksempel og alle kommende kodeeksempler, er ovenstående renderfunktion det, du har brug for.

Det andet argument for ReactDOM.renderer destinations-DOM-elementet, som React vil overtage og kontrollere. I jsComplete React Playground kan du bare bruge den specielle variabel mountNode.

JavaScript REPL og Playground til React.js

Test moderne JavaScript og React.js-kode i browseren uden nogen konfigurationer jscomplete.com/react

Bemærk følgende om eksempel 1:

  • Komponentnavnet starter med et stort bogstav. Dette er påkrævet, da vi har at gøre med en blanding af HTML-elementer og React-elementer. Navne på små bogstaver er forbeholdt HTML-elementer. Faktisk skal du prøve at navngive React-komponenten bare “knap” og se, hvordan ReactDOM vil ignorere funktionen og gengiver en almindelig tom HTML-knap.
  • Hver komponent modtager en liste over attributter, ligesom HTML-elementer. I React kaldes denne liste rekvisitter . Med en funktionskomponent kan du dog navngive det uanset hvad.
  • Vi skrev underligt, hvad der ligner HTML i det returnerede output af Buttonfunktionskomponenten ovenfor. Dette er hverken JavaScript eller HTML, og det er ikke engang React.js. Men det er så populært, at det blev standard i React-applikationer. Det hedder JSX, og det er en JavaScript-udvidelse. JSX er også et kompromis ! Gå videre og prøv at returnere ethvert andet HTML-element inden i funktionen ovenfor og se, hvordan de alle understøttes (for eksempel returnere et tekstinputelement).

Grundlæggende nr. 2: Hvad er JSX?

Eksempel 1 ovenfor kan skrives i ren React.js uden JSX som følger:

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

Den createElementfunktion er den vigtigste funktion i React øverste niveau API. Det er 1 af i alt 8 ting på det niveau, du har brug for at lære. Så lille er React API.

Ligesom DOM selv har en document.createElementfunktion til at oprette et element specificeret af et tagnavn, er React's createElementfunktion en funktion på højere niveau, der kan gøre hvad der document.createElementgør, men det kan også bruges til at oprette et element til at repræsentere en React-komponent. Vi gjorde sidstnævnte, da vi brugte Buttonkomponenten i eksempel 2 ovenfor.

I modsætning til accepterer document.createElementReact's createElementet dynamisk antal argumenter efter det andet, der repræsenterer børnene til det oprettede element. Så createElementopretter faktisk et træ .

Her er et eksempel på det:

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

Bemærk et par ting om eksemplet ovenfor:

  • InputFormer ikke en React-komponent; det er bare et React- element . Dette er grunden til, at vi brugte det direkte i ReactDOM.renderopkaldet og ikke med />.
  • 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