Komponenty klasy React
Przed React 16.8 komponenty Class były jedynym sposobem śledzenia stanu i cyklu życia komponentu React. Komponenty funkcyjne zostały uznane za „bezstanowe”.
Po dodaniu hooków komponenty Function są teraz prawie równoważne komponentom Class. Różnice są tak niewielkie, że prawdopodobnie nigdy nie będziesz musiał używać komponentu Class w React.
Mimo że preferowane są komponenty funkcyjne, nie ma obecnie planów usunięcia komponentów klasowych z Reacta.
W tej sekcji dowiesz się, jak używać komponentów klas w React.
Możesz pominąć tę sekcję i zamiast tego użyć składników funkcyjnych.
Reaguj Komponenty
Komponenty to niezależne i wielokrotnego użytku bity kodu. Służą temu samemu celowi co funkcje JavaScript, ale działają w izolacji i zwracają kod HTML za pomocą funkcji render().
Komponenty dzielą się na dwa typy, komponenty klasy i komponenty funkcyjne. W tym rozdziale dowiesz się o komponentach klas.
Utwórz komponent klasy
Podczas tworzenia komponentu React nazwa komponentu musi zaczynać się od wielkiej litery.
Komponent musi zawierać extends React.Component
instrukcję, która tworzy dziedziczenie po React.Component i daje twojemu komponentowi dostęp do funkcji React.Component.
Komponent wymaga również render()
metody, ta metoda zwraca kod HTML.
Przykład
Utwórz komponent klasy o nazwieCar
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Teraz Twoja aplikacja React ma komponent o nazwie Car, który zwraca
<h2>
element.
Aby użyć tego komponentu w swojej aplikacji, użyj podobnej składni jak normalny HTML:
<Car />
Przykład
Wyświetl Car
komponent w elemencie „root”:
ReactDOM.render(<Car />, document.getElementById('root'));
Zostać certyfikowanym!
95 $ ZAPISZ
Konstruktor komponentów
Jeśli w twoim komponencie istnieje
funkcja, zostanie ona wywołana, gdy komponent zostanie zainicjowany.constructor()
Funkcja konstruktora to miejsce, w którym inicjujesz właściwości komponentu.
W React właściwości komponentów powinny być przechowywane w obiekcie o nazwie
state
.
Więcej o tym dowiesz się state
w dalszej części tego samouczka.
Funkcja konstruktora jest również miejscem, w którym honorujesz dziedziczenie komponentu nadrzędnego super()
, dołączając instrukcję, która wykonuje funkcję konstruktora komponentu nadrzędnego, a twój komponent ma dostęp do wszystkich funkcji komponentu nadrzędnego ( React.Component
).
Przykład
Utwórz funkcję konstruktora w komponencie Car i dodaj właściwość koloru:
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a Car!</h2>;
}
}
Użyj właściwości color w funkcji render():
Przykład
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a {this.state.color} Car!</h2>;
}
}
Rekwizyty
Innym sposobem obsługi właściwości komponentu jest użycie props
.
Rekwizyty są jak argumenty funkcji i wysyłasz je do komponentu jako atrybuty.
Więcej o tym dowiesz się props
w następnym rozdziale.
Przykład
Użyj atrybutu, aby przekazać kolor do komponentu Car i użyj go w funkcji 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'));
Rekwizyty w Konstruktorze
Jeśli twój komponent ma funkcję konstruktora, właściwości powinny być zawsze przekazywane do konstruktora, a także do React.Component za pomocą super()
metody.
Przykład
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'));
Komponenty w Komponentach
Możemy odnosić się do komponentów wewnątrz innych komponentów:
Przykład
Użyj komponentu Samochód w komponencie Garaż:
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'));
Komponenty w plikach
React polega na ponownym wykorzystaniu kodu, a wstawienie niektórych komponentów do oddzielnych plików może być sprytne.
Aby to zrobić, utwórz nowy plik z .js
rozszerzeniem pliku i umieść w nim kod:
Zauważ, że plik musi zaczynać się od zaimportowania Reacta (jak poprzednio) i musi kończyć się instrukcją export default Car;
.
Przykład
To jest nowy plik, nazwaliśmy go Car.js
:
import React from 'react';
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
export default Car;
Aby móc korzystać z Car
komponentu, musisz zaimportować plik w swojej aplikacji.
Przykład
Teraz importujemy Car.js
plik w aplikacji i możemy używać
Car
komponentu tak, jakby został tutaj utworzony.
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './Car.js';
ReactDOM.render(<Car />, document.getElementById('root'));
Stan komponentu klasy React
Komponenty React Class mają wbudowany state
obiekt.
Być może zauważyłeś, że użyliśmy state
wcześniej w sekcji konstruktora komponentów.
Obiekt state
to miejsce, w którym przechowujesz wartości właściwości, które należą do komponentu.
Gdy state
obiekt się zmieni, komponent jest ponownie renderowany.
Tworzenie obiektu stanu
Obiekt stanu jest inicjowany w konstruktorze:
Przykład
Określ state
obiekt w metodzie konstruktora:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
Obiekt stanu może zawierać dowolną liczbę właściwości:
Przykład
Określ wszystkie właściwości potrzebne Twojemu komponentowi:
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>
);
}
}
Korzystanie z state
obiektu
Odwołaj się do state
obiektu w dowolnym miejscu w komponencie, używając
składni:this.state.propertyname
Przykład:
Odnieś się do state
obiektu w
render()
metodzie:
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>
);
}
}
Zmiana state
obiektu
Aby zmienić wartość w obiekcie stanu, użyj this.setState()
metody.
Gdy wartość w state
obiekcie ulegnie zmianie, komponent zostanie ponownie wyrenderowany, co oznacza, że dane wyjściowe zmienią się zgodnie z nowymi wartościami.
Przykład:
Dodaj przycisk ze onClick
zdarzeniem, które zmieni właściwość koloru:
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>
);
}
}
Zawsze używaj setState()
metody do zmiany obiektu stanu, zapewni to, że komponent będzie wiedział, że został zaktualizowany i wywoła metodę render() (i wszystkie inne metody cyklu życia).
Cykl życia komponentów
Każdy komponent w React ma cykl życia, który możesz monitorować i manipulować podczas jego trzech głównych faz.
Te trzy fazy to: Montowanie , Aktualizacja i Odmontowywanie .
Montowanie
Montaż polega na włożeniu elementów do DOM.
React ma cztery wbudowane metody, które są wywoływane w tej kolejności podczas montowania komponentu:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
Metoda render()
jest wymagana i zawsze będzie wywoływana, pozostałe są opcjonalne i zostaną wywołane, jeśli je zdefiniujesz.
constructor
Metoda constructor()
jest wywoływana przed wszystkim innym, gdy komponent jest inicjowany i jest to naturalne miejsce do ustawienia początkowej state
i innych początkowych wartości.
Metoda constructor()
jest wywoływana z
props
argumentami , jako i zawsze powinieneś zacząć od wywołania super(props)
przed czymkolwiek innym, to zainicjuje metodę konstruktora rodzica i pozwoli komponentowi dziedziczyć metody od swojego rodzica ( React.Component
).
Przykład:
Metoda constructor
jest wywoływana przez React za każdym razem, gdy tworzysz komponent:
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
Metoda getDerivedStateFromProps()
jest wywoływana tuż przed renderowaniem elementu(ów) w DOM.
Jest to naturalne miejsce na ustawienie state
obiektu na podstawie inicjału
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'));