Componentes de la clase React
Antes de React 16.8, los componentes de clase eran la única forma de rastrear el estado y el ciclo de vida en un componente de React. Los componentes de función se consideraron "sin estado".
Con la adición de Hooks, los componentes Function ahora son casi equivalentes a los componentes Class. Las diferencias son tan pequeñas que probablemente nunca necesitarás usar un componente Class en React.
Aunque se prefieren los componentes de función, no hay planes actuales para eliminar los componentes de clase de React.
Esta sección le dará una descripción general de cómo usar los componentes de clase en React.
Siéntase libre de omitir esta sección y usar Componentes de función en su lugar.
Reaccionar componentes
Los componentes son bits de código independientes y reutilizables. Tienen el mismo propósito que las funciones de JavaScript, pero funcionan de forma aislada y devuelven HTML a través de una función render().
Los componentes vienen en dos tipos, componentes de Clase y componentes de Función, en este capítulo aprenderá acerca de los componentes de Clase.
Crear un componente de clase
Al crear un componente React, el nombre del componente debe comenzar con una letra mayúscula.
El componente debe incluir la extends React.Component
declaración, esta declaración crea una herencia para React.Component y le da a su componente acceso a las funciones de React.Component.
El componente también requiere un render()
método, este método devuelve HTML.
Ejemplo
Cree un componente de Clase llamado Car
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Ahora su aplicación React tiene un componente llamado Car, que devuelve un
<h2>
elemento.
Para usar este componente en su aplicación, use una sintaxis similar a la de HTML normal:
<Car />
Ejemplo
Muestre el Car
componente en el elemento "raíz":
ReactDOM.render(<Car />, document.getElementById('root'));
¡Obtener la certificación!
$95 INSCRÍBETE
Constructor de componentes
Si hay una
función en su componente, esta función se llamará cuando se inicie el componente.constructor()
La función constructora es donde inicia las propiedades del componente.
En React, las propiedades de los componentes deben mantenerse en un objeto llamado
state
.
Aprenderá más sobre esto más state
adelante en este tutorial.
La función constructora también es donde respeta la herencia del componente principal al incluir la super()
instrucción, que ejecuta la función constructora del componente principal, y su componente tiene acceso a todas las funciones del componente principal ( React.Component
).
Ejemplo
Cree una función constructora en el componente Car y agregue una propiedad de color:
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a Car!</h2>;
}
}
Use la propiedad de color en la función render():
Ejemplo
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a {this.state.color} Car!</h2>;
}
}
Accesorios
Otra forma de manejar las propiedades de los componentes es usando props
.
Los accesorios son como argumentos de función y los envía al componente como atributos.
Aprenderá más props
en el próximo capítulo.
Ejemplo
Use un atributo para pasar un color al componente Car y utilícelo en la función 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'));
Accesorios en el Constructor
Si su componente tiene una función de constructor, los accesorios siempre deben pasarse al constructor y también al React.Component a través del super()
método.
Ejemplo
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'));
Componentes en Componentes
Podemos referirnos a componentes dentro de otros componentes:
Ejemplo
Utilice el componente Coche dentro del componente Garaje:
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'));
Componentes en archivos
React tiene que ver con la reutilización del código, y puede ser inteligente insertar algunos de sus componentes en archivos separados.
Para hacer eso, cree un nuevo archivo con una .js
extensión de archivo y coloque el código dentro:
Tenga en cuenta que el archivo debe comenzar importando React (como antes) y debe terminar con la instrucción export default Car;
.
Ejemplo
Este es el nuevo archivo, lo llamamos Car.js
:
import React from 'react';
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
export default Car;
Para poder utilizar el Car
componente, debe importar el archivo en su aplicación.
Ejemplo
Ahora importamos el Car.js
archivo en la aplicación y podemos usar el
Car
componente como si se hubiera creado aquí.
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './Car.js';
ReactDOM.render(<Car />, document.getElementById('root'));
Estado del componente de la clase React
Los componentes de React Class tienen un state
objeto incorporado.
Es posible que haya notado que usamos state
anteriormente en la sección del constructor de componentes.
El state
objeto es donde almacena valores de propiedad que pertenecen al componente.
Cuando el state
objeto cambia, el componente se vuelve a renderizar.
Creando el objeto de estado
El objeto de estado se inicializa en el constructor:
Ejemplo
Especifique el state
objeto en el método constructor:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
El objeto de estado puede contener tantas propiedades como desee:
Ejemplo
Especifique todas las propiedades que necesita su componente:
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 el state
Objeto
Haga referencia al state
objeto en cualquier parte del componente utilizando la
sintaxis:this.state.propertyname
Ejemplo:
Consulte el state
objeto en el
render()
método:
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>
);
}
}
Cambiar el state
objeto
Para cambiar un valor en el objeto de estado, use el this.setState()
método.
Cuando cambia un valor en el state
objeto, el componente se volverá a representar, lo que significa que la salida cambiará de acuerdo con los nuevos valores.
Ejemplo:
Agrega un botón con un onClick
evento que cambiará la propiedad del color:
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>
);
}
}
Utilice siempre el setState()
método para cambiar el objeto de estado, se asegurará de que el componente sepa que se ha actualizado y llame al método render() (y a todos los demás métodos del ciclo de vida).
Ciclo de vida de los componentes
Cada componente en React tiene un ciclo de vida que puedes monitorear y manipular durante sus tres fases principales.
Las tres fases son: Montaje , Actualización y Desmontaje .
Montaje
Montar significa poner elementos en el DOM.
React tiene cuatro métodos integrados que se llaman, en este orden, al montar un componente:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
El render()
método es obligatorio y siempre se llamará, los demás son opcionales y se llamarán si los define.
constructor
El constructor()
método se llama antes que nada, cuando se inicia el componente, y es el lugar natural para configurar los valores iniciales state
y otros valores iniciales.
El constructor()
método se llama con
props
, como argumentos, y siempre debe comenzar llamando a super(props)
antes que cualquier otra cosa, esto iniciará el método constructor del padre y permitirá que el componente herede métodos de su padre ( React.Component
).
Ejemplo:
React llama al constructor
método cada vez que 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
El getDerivedStateFromProps()
método se llama justo antes de representar los elementos en el DOM.
Este es el lugar natural para establecer el state
objeto en función de la inicial
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'));