1.state is used to control variables that appear in different states depending on the condition: for example, click Login, log in successfully, and the button turns red.
2. In the constructor, it is necessary to indicate the value of the change, which also indicates the data type of the data. Use the SetState method to update the state where it needs to be updated, and judge the status at the point where the UI is displayed, and the UI will automatically change as it changes.
3. Example:
Import React from ' React ' class Testclick extends React.component {constructor (props) {super (props);
This.state = {Clicked:false};
This.click = This.click.bind (this);
} click () {Console.log ("I was clicked");
This is ES5 's notation//this.setstate (function (prevstate,props) {//Console.log ("Pre-click" +this.state.clicked);
return {clicked:!this.state.clicked};
//
// });
This is ES6 's new syntax,=> before the argument, indicating the return value, the two parameters inside the default is brought over, one is the state is props this.setstate ((prevstate, props) = ({ Clicked:! (prevstate.clicked)}), function () {Console.log ("update Complete") Console.log ("after click" + this.state.c
licked);
});
}//The following are the major life cycle//render calls before Componentwillmount () {}//whether an update is required: This method does not rewrite: Beginning I rewrite, has been reported here is the value of indfine, clearly transmitted by the Boolean
Shouldcomponentupdate () {//Console.log (' need to be updated '); }//will update Componentwillupdate () {}//hasUpdated componentdidupdate () {}//accepted to New prop Componentwillreceiveprops () {}//After first render call Componen
Tdidmount () {//this.interval=setinterval (() =>this.click (), 1000)}//Remove Componentwillunmount () {
Clearimmediate (This.interval); } render () {var style = {backgroundColor:this.state.clicked?
' #000000 ': ' #ff0000 '}; var text = this.state.clicked?
' Open state ': ' Off state ';
Console.log (text);
Return (<div> <button Style={style} onclick={this.click}> point I'll try </button> <p> is open: {this.state.clicked} <span>{this.state.clicked?
' Open state ': ' Off state '}</span></p> </div>); }} export default Testclick;
4. Calling methods
Add the view to the App.js
Import React, {Component} from ' React ';
Import logo from './logo.svg ';
Import './app.css ';
Import Testclick from "./testclick";
Class App extends Component {
render () {
return (
<div classname= "app" >
5. Actual display effect: Click the button, the following text will show the current switch state, the color of the button will be changed.