Home >Web Front-end >JS Tutorial >Detailed explanation of state usage in React
This time I will bring you a detailed explanation of the use of state in React, what are the precautions for using state in React, the following is a practical case, let's take a look.
state can be understood as props. The difference is that props are read-only, while state is read-writeable. When the state changes, the render method will be re-executed to render the entire DOM tree. During the rendering process, a diff algorithm will be used to calculate which DOMs have been updated, thereby improving performance.
Before using state, you must initialize it getInitialState
To change state, you must use setState
getInitialState
This method will be used every time it is rendered. is called once.
//es5 var StateComponent = React.createClass({ getInitialState: function(){ return { text: '' } }, change: function(event){ this.setState({text: event.target.value}); }, render: function(){ return ( <p> <p><input type="text" onChange={this.change}/></p> <p>{this.state.text}</p> </p> ) } }) //es6 import React from 'react'; import ReactDOM from 'react-dom'; class Component1 extends React.Component{ state = { text: '' } change(event){ this.setState({text: event.target.value}); }, render(){ return ( <p> <p><input type="text" onChange={this.change}/></p> <p>{this.state.text}</p> </p> ) } }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the steps to select li highlighting in react
JSON and Math use case analysis in JS
The above is the detailed content of Detailed explanation of state usage in React. For more information, please follow other related articles on the PHP Chinese website!