Home > Web Front-end > JS Tutorial > body text

Detailed explanation of state usage in React

php中世界最好的语言
Release: 2018-05-24 14:26:42
Original
2322 people have browsed it

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

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>
        )
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!