Componenti della classe di reazione
Prima di React 16.8, i componenti di classe erano l'unico modo per tenere traccia dello stato e del ciclo di vita di un componente di React. I componenti della funzione erano considerati "senza stato".
Con l'aggiunta di Hook, i componenti Function sono ora quasi equivalenti ai componenti Class. Le differenze sono così minime che probabilmente non avrai mai bisogno di usare un componente Class in React.
Anche se i componenti di funzione sono preferiti, non ci sono piani attuali per rimuovere i componenti di classe da React.
Questa sezione ti darà una panoramica su come usare i componenti della classe in React.
Sentiti libero di saltare questa sezione e usa invece i componenti della funzione.
Componenti di reazione
I componenti sono bit di codice indipendenti e riutilizzabili. Hanno lo stesso scopo delle funzioni JavaScript, ma funzionano in isolamento e restituiscono HTML tramite una funzione render().
I componenti sono di due tipi, componenti di classe e componenti di funzione, in questo capitolo imparerai i componenti di classe.
Crea un componente di classe
Quando si crea un componente React, il nome del componente deve iniziare con una lettera maiuscola.
Il componente deve includere l' extends React.Component
istruzione, questa istruzione crea un'eredità in React.Component e fornisce al tuo componente l'accesso alle funzioni di React.Component.
Il componente richiede anche un render()
metodo, questo metodo restituisce HTML.
Esempio
Crea un componente di classe chiamatoCar
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Ora la tua applicazione React ha un componente chiamato Car, che restituisce un
<h2>
elemento.
Per utilizzare questo componente nella tua applicazione, usa una sintassi simile a quella del normale HTML:
<Car />
Esempio
Visualizza il Car
componente nell'elemento "root":
ReactDOM.render(<Car />, document.getElementById('root'));
Ottieni la certificazione!
ISCRIVITI A $95
Costruttore di componenti
Se è presente una
funzione nel componente, questa funzione verrà chiamata quando il componente viene avviato.constructor()
La funzione di costruzione è dove si avviano le proprietà del componente.
In React, le proprietà dei componenti dovrebbero essere mantenute in un oggetto chiamato
state
.
Imparerai di più più state
avanti in questo tutorial.
La funzione di costruzione è anche il punto in cui si rispetta l'ereditarietà del componente padre includendo l' super()
istruzione, che esegue la funzione di costruzione del componente padre, e il proprio componente ha accesso a tutte le funzioni del componente padre ( React.Component
).
Esempio
Crea una funzione di costruzione nel componente Car e aggiungi una proprietà color:
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a Car!</h2>;
}
}
Usa la proprietà color nella funzione render():
Esempio
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a {this.state.color} Car!</h2>;
}
}
Puntelli
Un altro modo per gestire le proprietà dei componenti consiste nell'usare props
.
Gli oggetti di scena sono come argomenti di funzione e li invii nel componente come attributi.
Imparerai di più props
nel prossimo capitolo.
Esempio
Usa un attributo per passare un colore al componente Car e usalo nella funzione render():
class Car extends React.Component {
render() {
return <h2>I am a {this.props.color} Car!</h2>;
}
}
ReactDOM.render(<Car color="red"/>, document.getElementById('root'));
Puntelli nel Costruttore
Se il tuo componente ha una funzione di costruzione, gli oggetti di scena dovrebbero sempre essere passati al costruttore e anche a React.Component tramite il super()
metodo.
Esempio
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'));
Componenti in Componenti
Possiamo fare riferimento a componenti all'interno di altri componenti:
Esempio
Usa il componente Auto all'interno del componente 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'));
Componenti nei file
React è incentrato sul riutilizzo del codice e può essere intelligente inserire alcuni dei tuoi componenti in file separati.
Per fare ciò, crea un nuovo file con .js
un'estensione di file e inserisci il codice al suo interno:
Si noti che il file deve iniziare importando React (come prima) e deve terminare con l'istruzione export default Car;
.
Esempio
Questo è il nuovo file, lo abbiamo chiamato Car.js
:
import React from 'react';
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
export default Car;
Per poter utilizzare il Car
componente, devi importare il file nella tua applicazione.
Esempio
Ora importiamo il Car.js
file nell'applicazione e possiamo utilizzare il
Car
componente come se fosse stato creato qui.
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './Car.js';
ReactDOM.render(<Car />, document.getElementById('root'));
Stato del componente della classe di reazione
I componenti di React Class hanno un state
oggetto incorporato.
Potresti aver notato che abbiamo usato state
in precedenza nella sezione del costruttore di componenti.
L' state
oggetto è il punto in cui vengono archiviati i valori delle proprietà che appartengono al componente.
Quando l' state
oggetto cambia, il componente esegue nuovamente il rendering.
Creazione dello stato Oggetto
L'oggetto state viene inizializzato nel costruttore:
Esempio
Specificare l' state
oggetto nel metodo del costruttore:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
L'oggetto stato può contenere tutte le proprietà che desideri:
Esempio
Specifica tutte le proprietà di cui il tuo componente ha bisogno:
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>
);
}
}
Usando l' state
Oggetto
Fare riferimento state
all'oggetto in qualsiasi punto del componente utilizzando la
sintassi:this.state.propertyname
Esempio:
Fare riferimento state
all'oggetto nel
render()
metodo:
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>
);
}
}
Modifica state
dell'oggetto
Per modificare un valore nell'oggetto stato, utilizzare il this.setState()
metodo.
Quando un valore state
nell'oggetto cambia, il componente verrà riprodotto, il che significa che l'output cambierà in base ai nuovi valori.
Esempio:
Aggiungi un pulsante con un onClick
evento che cambierà la proprietà del colore:
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>
);
}
}
Usa sempre il setState()
metodo per cambiare l'oggetto di stato, assicurerà che il componente sappia che è stato aggiornato e chiama il metodo render() (e tutti gli altri metodi del ciclo di vita).
Ciclo di vita dei componenti
Ogni componente in React ha un ciclo di vita che puoi monitorare e manipolare durante le sue tre fasi principali.
Le tre fasi sono: montaggio , aggiornamento e smontaggio .
Montaggio
Montare significa inserire elementi nel DOM.
React ha quattro metodi integrati che vengono chiamati, in questo ordine, durante il montaggio di un componente:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
Il render()
metodo è obbligatorio e sarà sempre chiamato, gli altri sono facoltativi e verranno chiamati se vengono definiti.
constructor
Il constructor()
metodo viene chiamato prima di ogni altra cosa, quando il componente viene avviato, ed è il luogo naturale per impostare i valori iniziali state
e altri valori iniziali.
Il constructor()
metodo viene chiamato con
props
, come argomenti, e dovresti sempre iniziare chiamando super(props)
prima di ogni altra cosa, questo avvierà il metodo costruttore del genitore e consentirà al componente di ereditare i metodi dal suo genitore ( React.Component
).
Esempio:
Il constructor
metodo viene chiamato, da React, ogni volta che si crea un componente:
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
Il getDerivedStateFromProps()
metodo viene chiamato subito prima del rendering degli elementi nel DOM.
Questo è il luogo naturale per impostare l' state
oggetto in base all'iniziale
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:
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
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'));