Componenten van de reactieklasse


Vóór React 16.8 waren Class-componenten de enige manier om de status en levenscyclus van een React-component te volgen. Functiecomponenten werden als "staatloos" beschouwd.

Met de toevoeging van Hooks zijn Function-componenten nu bijna gelijk aan Class-componenten. De verschillen zijn zo klein dat je waarschijnlijk nooit een Class-component in React hoeft te gebruiken.

Hoewel Function-componenten de voorkeur hebben, zijn er momenteel geen plannen om Class-componenten uit React te verwijderen.

Deze sectie geeft je een overzicht van het gebruik van Class-componenten in React.

Voel je vrij om deze sectie over te slaan en in plaats daarvan functiecomponenten te gebruiken.


Reageer componenten

Componenten zijn onafhankelijke en herbruikbare stukjes code. Ze hebben hetzelfde doel als JavaScript-functies, maar werken afzonderlijk en retourneren HTML via een render()-functie.

Componenten zijn er in twee soorten, Klasse-componenten en Functiecomponenten. In dit hoofdstuk leert u over Klasse-componenten.


Een klascomponent maken

Bij het aanmaken van een React-component moet de naam van de component beginnen met een hoofdletter.

De component moet het extends React.Componentstatement bevatten, dit statement creëert een erfenis naar React.Component, en geeft je component toegang tot de functies van React.Component.

De component vereist ook een render()methode, deze methode retourneert HTML.

Voorbeeld

Maak een Klasse-component met de naamCar

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
  }
}

<h2>Nu heeft je React-applicatie een component genaamd Car, die een element retourneert .

Om dit onderdeel in uw toepassing te gebruiken, gebruikt u vergelijkbare syntaxis als normale HTML: <Car />

Voorbeeld

Geef de Carcomponent weer in het "root"-element:

ReactDOM.render(<Car />, document.getElementById('root'));


w3schools CERTIFIED . 2022

Gecertificeerd!

Voltooi de React-modules, doe de oefeningen, doe het examen en word w3schools gecertificeerd!!

$95 INSCHRIJVEN

Component Constructor

Als er een constructor()functie in uw component is, wordt deze functie aangeroepen wanneer de component wordt gestart.

De constructorfunctie is waar u de eigenschappen van de component start.

In React moeten componenteigenschappen worden bewaard in een object met de naam state.

stateLater in deze tutorial leer je er meer over .

De constructorfunctie is ook waar u de overerving van de bovenliggende component respecteert door de super() instructie op te nemen, die de constructorfunctie van de bovenliggende component uitvoert, en uw component heeft toegang tot alle functies van de bovenliggende component ( React.Component).

Voorbeeld

Maak een constructorfunctie in de component Car en voeg een kleureigenschap toe:

class Car extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }
  render() {
    return <h2>I am a Car!</h2>;
  }
}

Gebruik de eigenschap color in de functie render():

Voorbeeld

class Car extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }
  render() {
    return <h2>I am a {this.state.color} Car!</h2>;
  }
}


Rekwisieten

Een andere manier om met componenteigenschappen om te gaan, is door props.

Props zijn als functieargumenten en je stuurt ze als attributen naar de component.

propsIn het volgende hoofdstuk leest u er meer over .

Voorbeeld

Gebruik een attribuut om een ​​kleur door te geven aan de Car-component en gebruik deze in de render()-functie:

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.color} Car!</h2>;
  }
}

ReactDOM.render(<Car color="red"/>, document.getElementById('root'));


Rekwisieten in de Constructor

Als je component een constructorfunctie heeft, moeten de rekwisieten altijd worden doorgegeven aan de constructor en ook aan de React.Component via de super()methode.

Voorbeeld

class Car extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h2>I am a {this.props.model}!</h2>;
  }
}

ReactDOM.render(<Car model="Mustang"/>, document.getElementById('root'));


Componenten in Componenten

We kunnen verwijzen naar componenten in andere componenten:

Voorbeeld

Gebruik de component Auto in de component Garage:

class Car extends React.Component {
  render() {
    return <h2>I am a Car!</h2>;
  }
}

class Garage extends React.Component {
  render() {
    return (
      <div>
      <h1>Who lives in my Garage?</h1>
      <Car />
      </div>
    );
  }
}

ReactDOM.render(<Garage />, document.getElementById('root'));


Componenten in Bestanden

Bij React draait alles om het hergebruiken van code, en het kan slim zijn om sommige van je componenten in aparte bestanden te plaatsen.

Om dat te doen, maakt u een nieuw bestand met een .js bestandsextensie en plaatst u de code erin:

Merk op dat het bestand moet beginnen met het importeren van React (zoals eerder), en het moet eindigen met de instructie export default Car;.

Voorbeeld

Dit is het nieuwe bestand, we noemden het Car.js:

import React from 'react';

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
  }
}

export default Car;

Om het Caronderdeel te kunnen gebruiken, moet u het bestand in uw applicatie importeren.

Voorbeeld

Nu importeren we het Car.jsbestand in de toepassing en kunnen we het Car onderdeel gebruiken alsof het hier is gemaakt.

import React from 'react';
import ReactDOM from 'react-dom';
import Car from './Car.js';

ReactDOM.render(<Car />, document.getElementById('root'));


Reageerklasse Component Staat

React Class-componenten hebben een ingebouwd stateobject.

Het is je misschien opgevallen dat we stateeerder in de component constructor sectie hebben gebruikt.

Het stateobject is waar u eigenschapswaarden opslaat die bij de component horen.

Wanneer het stateobject verandert, wordt de component opnieuw weergegeven.


Het statusobject maken

Het state-object wordt geïnitialiseerd in de constructor:

Voorbeeld

Specificeer het stateobject in de constructormethode:

class Car extends React.Component {
  constructor(props) {
    super(props);
  this.state = {brand: "Ford"};
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

Het state-object kan zoveel eigenschappen bevatten als u wilt:

Voorbeeld

Specificeer alle eigenschappen die uw component nodig heeft:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My Car</h1>
      </div>
    );
  }
}

Het stateobject gebruiken

Verwijs naar het stateobject ergens in de component met behulp van de syntaxis:this.state.propertyname

Voorbeeld:

Raadpleeg het stateobject in de render()methode:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
      </div>
    );
  }
}


Het stateobject wijzigen

Gebruik de this.setState()methode om een ​​waarde in het statusobject te wijzigen.

Wanneer een waarde in het stateobject verandert, wordt de component opnieuw weergegeven, wat betekent dat de uitvoer zal veranderen volgens de nieuwe waarde(n).

Voorbeeld:

Voeg een knop toe met een onClickgebeurtenis die de kleureigenschap zal wijzigen:

class Car extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  changeColor = () => {
    this.setState({color: "blue"});
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
        <button
          type="button"
          onClick={this.changeColor}
        >Change color</button>
      </div>
    );
  }
}

Gebruik altijd de setState()methode om het statusobject te wijzigen, het zorgt ervoor dat het onderdeel weet dat het is bijgewerkt en roept de methode render() aan (en alle andere levenscyclusmethoden).


Levenscyclus van componenten

Elk onderdeel in React heeft een levenscyclus die je kunt volgen en manipuleren tijdens de drie hoofdfasen.

De drie fasen zijn: Montage , Updaten en Ontkoppelen .


Montage

Monteren betekent elementen in de DOM plaatsen.

React heeft vier ingebouwde methoden die in deze volgorde worden aangeroepen bij het monteren van een component:

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

De render()methode is vereist en wordt altijd aangeroepen, de andere zijn optioneel en worden aangeroepen als u ze definieert.


constructor

De constructor()methode wordt voor alles aangeroepen, wanneer de component wordt gestart, en het is de natuurlijke plaats om de initiële stateen andere initiële waarden in te stellen.

De constructor()methode wordt aangeroepen met de props, als argumenten, en je moet altijd beginnen met het aanroepen van de super(props)voor iets anders, dit zal de constructormethode van de ouder starten en de component de methodes van zijn bovenliggende ( React.Component) erven.

Voorbeeld:

De constructormethode wordt door React aangeroepen elke keer dat je een component maakt:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


getDerivedStateFromProps

De getDerivedStateFromProps()methode wordt aangeroepen vlak voordat de elementen in de DOM worden weergegeven.

Dit is de natuurlijke plaats om het stateobject in te stellen op basis van de initiaal props.

It takes state as an argument, and returns an object with changes to the state.

The example below starts with the favorite color being "red", but the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute:

Example:

The getDerivedStateFromProps method is called right before the render method:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));


render

The render() method is required, and is the method that actually outputs the HTML to the DOM.

Example:

A simple component with a simple render() method:

class Header extends React.Component {
  render() {
    return (
      <h1>This is the content of the Header component</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


componentDidMount

The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already placed in the DOM.

Example:

At first my favorite color is red, but give me a second, and it is yellow instead:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


Updating

The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the component's state or props.

React has five built-in methods that gets called, in this order, when a component is updated:

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

The render() method is required and will always be called, the others are optional and will be called if you define them.


getDerivedStateFromProps

Also at updates the getDerivedStateFromProps method is called. This is the first method that is called when a component gets updated.

This is still the natural place to set the state object based on the initial props.

The example below has a button that changes the favorite color to blue, but since the getDerivedStateFromProps() method is called, which updates the state with the color from the favcol attribute, the favorite color is still rendered as yellow:

Example:

If the component gets updated, the getDerivedStateFromProps() method is called:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));


shouldComponentUpdate

In the shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not.

The default value is true.

The example below shows what happens when the shouldComponentUpdate() method returns false:

Example:

Stop the component from rendering at any update:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

Example:

Same example as above, but this time the shouldComponentUpdate() method returns true instead:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return true;
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


render

The render() method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.

The example below has a button that changes the favorite color to blue:

Example:

Click the button to make a change in the component's state:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


getSnapshotBeforeUpdate

In the getSnapshotBeforeUpdate() method you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update.

If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate() method, otherwise you will get an error.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".

When the component has been mounted, a timer changes the state, and after one second, the favorite color becomes "yellow".

This action triggers the update phase, and since this component has a getSnapshotBeforeUpdate() method, this method is executed, and writes a message to the empty DIV1 element.

Then the componentDidUpdate() method is executed and writes a message in the empty DIV2 element:

 

Example:

Use the getSnapshotBeforeUpdate() method to find out what the state object looked like before the update:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "Before the update, the favorite was " + prevState.favoritecolor;
  }
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <div id="div1"></div>
        <div id="div2"></div>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


componentDidUpdate

The componentDidUpdate method is called after the component is updated in the DOM.

The example below might seem complicated, but all it does is this:

When the component is mounting it is rendered with the favorite color "red".

When the component has been mounted, a timer changes the state, and the color becomes "yellow".

This action triggers the update phase, and since this component has a componentDidUpdate method, this method is executed and writes a message in the empty DIV element:

Example:

The componentDidUpdate method is called after the update has been rendered in the DOM:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  componentDidUpdate() {
    document.getElementById("mydiv").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <div id="mydiv"></div>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));


Unmounting

The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it.

React has only one built-in method that gets called when a component is unmounted:

  • componentWillUnmount()

componentWillUnmount

The componentWillUnmount method is called when the component is about to be removed from the DOM.

Example:

Click the button to delete the header:

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }
  delHeader = () => {
    this.setState({show: false});
  }
  render() {
    let myheader;
    if (this.state.show) {
      myheader = <Child />;
    };
    return (
      <div>
      {myheader}
      <button type="button" onClick={this.delHeader}>Delete Header</button>
      </div>
    );
  }
}

class Child extends React.Component {
  componentWillUnmount() {
    alert("The component named Header is about to be unmounted.");
  }
  render() {
    return (
      <h1>Hello World!</h1>
    );
  }
}

ReactDOM.render(<Container />, document.getElementById('root'));