Reageer Klaskomponente


Voor React 16.8 was klaskomponente die enigste manier om toestand en lewensiklus op 'n React-komponent na te spoor. Funksiekomponente is as "staatloos" beskou.

Met die byvoeging van Hakies, is Funksie-komponente nou amper gelykstaande aan Klas-komponente. Die verskille is so gering dat u waarskynlik nooit 'n klaskomponent in React hoef te gebruik nie.

Alhoewel funksiekomponente verkies word, is daar geen huidige planne om klaskomponente van React te verwyder nie.

Hierdie afdeling sal jou 'n oorsig gee van hoe om klaskomponente in React te gebruik.

Slaan gerus hierdie afdeling oor, en gebruik eerder Funksie-komponente.


Reageer komponente

Komponente is onafhanklike en herbruikbare stukkies kode. Hulle dien dieselfde doel as JavaScript-funksies, maar werk in isolasie en gee HTML terug via 'n render()-funksie.

Komponente kom in twee tipes voor, Klaskomponente en Funksiekomponente, in hierdie hoofstuk sal jy leer oor Klaskomponente.


Skep 'n klaskomponent

Wanneer 'n React-komponent geskep word, moet die komponent se naam met 'n hoofletter begin.

Die komponent moet die extends React.Componentstelling insluit, hierdie stelling skep 'n erfenis na React.Component, en gee jou komponent toegang tot React.Component se funksies.

Die komponent vereis ook 'n render()metode, hierdie metode gee HTML terug.

Voorbeeld

Skep 'n Klaskomponent genaamdCar

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

Nou het jou React-toepassing 'n komponent genaamd Car, wat 'n <h2>element terugstuur.

Om hierdie komponent in jou toepassing te gebruik, gebruik soortgelyke sintaksis as normale HTML: <Car />

Voorbeeld

Vertoon die Carkomponent in die "root" element:

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


w3schools CERTIFIED . 2022

Word gesertifiseer!

Voltooi die React-modules, doen die oefeninge, neem die eksamen en word w3schools-gesertifiseer!!

$95 INSKRIF

Komponent Konstrukteur

As daar 'n constructor()funksie in jou komponent is, sal hierdie funksie geroep word wanneer die komponent begin word.

Die konstruktorfunksie is waar jy die komponent se eienskappe inisieer.

In React moet komponenteienskappe in 'n voorwerp genaamd gehou word state.

stateJy sal later in hierdie tutoriaal meer daaroor leer .

Die konstruktorfunksie is ook waar jy die oorerwing van die ouerkomponent eerbiedig deur die super() stelling in te sluit, wat die ouerkomponent se konstruktorfunksie uitvoer, en jou komponent het toegang tot al die funksies van die ouerkomponent ( React.Component).

Voorbeeld

Skep 'n konstruktorfunksie in die Car-komponent, en voeg 'n kleureienskap by:

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

Gebruik die kleur eienskap in die render() funksie:

Voorbeeld

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


Rekwisiete

Nog 'n manier om komponenteienskappe te hanteer is deur props.

Rekwisiete is soos funksie-argumente, en jy stuur dit in die komponent as eienskappe.

Jy sal meer oor propsin die volgende hoofstuk leer.

Voorbeeld

Gebruik 'n kenmerk om 'n kleur na die Car-komponent deur te gee, en gebruik dit in die render()-funksie:

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

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


Rekwisiete in die Konstrukteur

As jou komponent 'n konstruktorfunksie het, moet die rekwisiete altyd deur die super()metode aan die konstruktor en ook na die React.Component deurgegee word.

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


Komponente in komponente

Ons kan verwys na komponente binne ander komponente:

Voorbeeld

Gebruik die Motor-komponent binne die Garage-komponent:

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


Komponente in lêers

React gaan alles oor die hergebruik van kode, en dit kan slim wees om sommige van jou komponente in aparte lêers in te voeg.

Om dit te doen, skep 'n nuwe lêer met 'n .js lêeruitbreiding en plaas die kode daarin:

Let daarop dat die lêer moet begin deur React in te voer (soos voorheen), en dit moet eindig met die stelling export default Car;.

Voorbeeld

Dit is die nuwe lêer, ons het dit genoem Car.js:

import React from 'react';

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

export default Car;

Om die Carkomponent te kan gebruik, moet jy die lêer in jou toepassing invoer.

Voorbeeld

Nou voer ons die Car.jslêer in die toepassing in, en ons kan die Car komponent gebruik asof dit hier geskep is.

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

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


Reageer Klaskomponenttoestand

React Class-komponente het 'n ingeboude statevoorwerp.

Jy het dalk opgemerk dat ons statevroeër in die komponentkonstruktorafdeling gebruik het.

Die stateobjek is waar jy eiendomswaardes stoor wat aan die komponent behoort.

Wanneer die statevoorwerp verander, word die komponent weergegee.


Die skep van die staatsobjek

Die toestandobjek word in die konstruktor geïnisialiseer:

Voorbeeld

Spesifiseer die stateobjek in die konstruktormetode:

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

Die staatsvoorwerp kan soveel eienskappe bevat as wat jy wil:

Voorbeeld

Spesifiseer al die eienskappe wat u komponent benodig:

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

Die gebruik van die statevoorwerp

Verwys na die statevoorwerp op enige plek in die komponent deur die sintaksis te gebruik:this.state.propertyname

Voorbeeld:

Verwys na die statevoorwerp in die render()metode:

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


Verander die statevoorwerp

Om 'n waarde in die toestandobjek te verander, gebruik die this.setState()metode.

Wanneer 'n waarde in die stateobjek verander, sal die komponent herweergegee word, wat beteken dat die uitset sal verander volgens die nuwe waarde(s).

Voorbeeld:

Voeg 'n knoppie by met 'n onClickgebeurtenis wat die kleureienskap sal verander:

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 altyd die setState()metode om die toestandobjek te verander, dit sal verseker dat die komponent weet dat dit opgedateer is en die render()-metode (en al die ander lewensiklusmetodes) oproep.


Lewensiklus van komponente

Elke komponent in React het 'n lewensiklus wat u tydens sy drie hooffases kan monitor en manipuleer.

Die drie fases is: Monteer , Opdateer en Ontkoppel .


Montering

Montering beteken om elemente in die DOM te plaas.

React het vier ingeboude metodes wat in hierdie volgorde genoem word wanneer 'n komponent gemonteer word:

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

Die render()metode word vereis en sal altyd genoem word, die ander is opsioneel en sal genoem word as jy hulle definieer.


constructor

Die constructor()metode word voor enigiets anders genoem wanneer die komponent geïnisieer word, en dit is die natuurlike plek om die aanvanklike stateen ander beginwaardes op te stel.

Die constructor()metode word genoem met die props, as argumente, en jy moet altyd begin deur die super(props)voor enigiets anders te noem, dit sal die ouer se konstruktormetode inisieer en laat die komponent toe om metodes van sy ouer te erf ( React.Component).

Voorbeeld:

Die constructormetode word deur React genoem elke keer as jy 'n komponent maak:

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

Die getDerivedStateFromProps()metode word genoem reg voor die lewering van die element(e) in die DOM.

Dit is die natuurlike plek om die statevoorwerp op grond van die voorletter te stel 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'));