De bedste reaktionseksempler

React (også kendt som React.js) er et af de mest populære JavaScript front end-udviklingsbiblioteker. Her er en samling af React-syntaks og -brug, som du kan bruge som en praktisk guide eller reference.

Eksempel på reaktionskomponent

Komponenter kan genbruges i React.js. Du kan indsprøjte værdi i rekvisitter som angivet nedenfor:

function Welcome(props) { return 

Hello, {props.name}

; } const element = ; ReactDOM.render( element, document.getElementById('root') );

name="Faisal Arkan"vil give værdi til {props.name}fra function Welcome(props)og returnere en komponent, der har givet værdi ved name="Faisal Arkan". Derefter gengiver React elementet til html.

Andre måder at deklarere komponenter på

Der er mange måder at deklarere komponenter, når du bruger React.js. Der er to slags komponenter, statsløse komponenter og stateful komponenter.

Stateful

Klassetype komponenter

class Cat extends React.Component { constructor(props) { super(props); this.state = { humor: 'happy' } } render() { return( 

{this.props.name}

{this.props.color}

); } }

Statsløse komponenter

Funktionelle komponenter (pilefunktion fra ES6)

const Cat = props => { return ( 

{props.name}

{props.color}

; ); };

Implicitte returkomponenter

const Cat = props =>

{props.name}

{props.color}

;

Reager fragmenteksempel

Fragmenter er måde at gengive flere elementer uden at bruge et indpakningselement. Når du forsøger at gengive elementer uden et vedlagte tag i JSX, vil du se fejlmeddelelsen Adjacent JSX elements must be wrapped in an enclosing tag. Dette skyldes, at når JSX transpilerer, opretter det elementer med deres tilsvarende tagnavne og ved ikke, hvilket tagnavn der skal bruges, hvis der findes flere elementer.

Tidligere var en hyppig løsning på dette at bruge en indpakningsdel til at løse dette problem. Imidlertid bragte version 16 af React tilføjelsen af Fragment, hvilket gør dette ikke længere nødvendigt.

Fragmentfungerer en indpakning uden at tilføje unødvendige divs til DOM. Du kan bruge den direkte fra React-importen eller dekonstruere den:

import React from 'react'; class MyComponent extends React.Component { render(){ return ( I am an element! I am another element  ); } } export default MyComponent;
// Deconstructed import React, { Component, Fragment } from 'react'; class MyComponent extends Component { render(){ return ( I am an element! I am another element  ); } } export default MyComponent;

Reager version 16.2 forenklede denne proces yderligere, så tomme JSX-tags kunne fortolkes som fragmenter:

return ( I am an element! I am another element  );

Reager JSX-eksempel

JSX

JSX er en forkortelse for JavaScript XML.

JSX er et udtryk, der bruger gyldige HTML-udsagn i JavaScript. Du kan tildele dette udtryk til en variabel og bruge det andetsteds. Du kan kombinere andre gyldige JavaScript-udtryk og JSX inden for disse HTML-sætninger ved at placere dem inden for seler ( {}). Babel kompilerer yderligere JSX til et objekt af typen React.createElement().

Enkeltlinje- og flerlinieudtryk

Enkeltlinjeudtryk er enkle at bruge.

const one = 

Hello World!

;

Når du har brug for flere linjer i et enkelt JSX-udtryk, skal du skrive koden inden for en enkelt parentes.

const two = ( 
    
  • Once
  • Twice
);

Brug kun HTML-tags

const greet = 

Hello World!

;

Kombinerer JavaScript-udtryk med HTML-tags

Vi kan bruge JavaScript-variabler inden for seler.

const who = "Quincy Larson"; const greet = 

Hello {who}!

;

Vi kan også kalde andre JavaScript-funktioner inden for seler.

function who() { return "World"; } const greet = 

Hello {who()}!

;

Kun en enkelt overordnet tag er tilladt

A JSX expression must have only one parent tag. We can add multiple tags nested within the parent element only.

// This is valid. const tags = ( 
    
  • Once
  • Twice
); // This is not valid. const tags = (

Hello World!

This is my special list:

  • Once
  • Twice
);

React State Example

State is the place where the data comes from.

We should always try to make our state as simple as possible and minimize the number of stateful components. If we have, for example, ten components that need data from the state, we should create one container component that will keep the state for all of them.

State is basically like a global object that is available everywhere in a component.

Example of a Stateful Class Component:

import React from 'react'; class App extends React.Component { constructor(props) { super(props); // We declare the state as shown below this.state = { x: "This is x from state", y: "This is y from state" } } render() { return ( 

{this.state.x}

{this.state.y}

); } } export default App;

Another Example:

import React from 'react'; class App extends React.Component { constructor(props) { super(props); // We declare the state as shown below this.state = { x: "This is x from state", y: "This is y from state" } } render() { let x1 = this.state.x; let y1 = this.state.y; return ( 

{x1}

{y1}

); } } export default App;

Updating State

You can change the data stored in the state of your application using the setState method on your component.

this.setState({ value: 1 });

Keep in mind that setState is asynchronous so you should be careful when using the current state to set a new state. A good example of this would be if you want to increment a value in your state.

The Wrong Way

this.setState({ value: this.state.value + 1 });

This can lead to unexpected behavior in your app if the code above is called multiple times in the same update cycle. To avoid this you can pass an updater callback function to setState instead of an object.

The Right Way

this.setState(prevState => ({ value: prevState.value + 1 }));

Updating State

You can change the data stored in the state of your application using the setState method on your component.

this.setState({value: 1});

Keep in mind that setState may be asynchronous so you should be careful when using the current state to set a new state. A good example of this would be if you want to increment a value in your state.

The Wrong Way
this.setState({value: this.state.value + 1});

This can lead to unexpected behavior in your app if the code above is called multiple times in the same update cycle. To avoid this you can pass an updater callback function to setState instead of an object.

The Right Way
this.setState(prevState => ({value: prevState.value + 1}));
The Cleaner Way
this.setState(({ value }) => ({ value: value + 1 }));

When only a limited number of fields in the state object is required, object destructing can be used for cleaner code.

React State VS Props Example

When we start working with React components, we frequently hear two terms. They are state and props. So, in this article we will explore what are those and how they differ.

State:

  • State is something that a component owns. It belongs to that particular component where it is defined. For example, a person’s age is a state of that person.
  • State is mutable. But it can be changed only by that component that owns it. As I only can change my age, not anyone else.
  • You can change a state by using this.setState()

See the below example to get an idea of state:

Person.js

 import React from 'react'; class Person extends React.Component{ constructor(props) { super(props); this.state = { age:0 this.incrementAge = this.incrementAge.bind(this) } incrementAge(){ this.setState({ age:this.state.age + 1; }); } render(){ return( My age is: {this.state.age} Grow me older !! ); } } export default Person;

In the above example, age is the state of Person component.

Props:

  • Props are similar to method arguments. They are passed to a component where that component is used.
  • Props is immutable. They are read-only.

See the below example to get an idea of Props:

Person.js

 import React from 'react'; class Person extends React.Component{ render(){ return( I am a {this.props.character} person. ); } } export default Person; const person = 

In the above example, const person = we are passing character = "good" prop to Person component.

It gives output as “I am a good person”, in fact I am.

There is lot more to learn on State and Props. Many things can be learnt by actually diving into coding. So get your hands dirty by coding.

React Higher-Order Component Example

In React, a Higher-Order Component (HOC) is a function that takes a component and returns a new component. Programmers use HOCs to achieve component logic reuse.

If you’ve used Redux’s connect, you’ve already worked with Higher-Order Components.

The core idea is:

const EnhancedComponent = enhance(WrappedComponent);

Hvor:

  • enhance er komponenten i højere orden;
  • WrappedComponenter den komponent, du vil forbedre; og
  • EnhancedComponent er den nye komponent oprettet.

Dette kan være kroppen af enhanceHOC:

function enhance(WrappedComponent) { return class extends React.Component { render() { const extraProp = 'This is an injected prop!'; return ( ); } } } 

I dette tilfælde enhancereturnerer en anonym klasse, der udvides React.Component. Denne nye komponent gør tre enkle ting:

  • Gengivelse af det WrappedComponentindre inden for et divelement;
  • At videregive sine egne rekvisitter til WrappedComponent; og
  • Injektion af en ekstra prop til WrappedComponent.

HOC'er er bare et mønster, der bruger kraften i React's kompositionsnatur. De tilføjer funktioner til en komponent . Der er mange flere ting, du kan gøre med dem!