react (two) controlled components react controlled components

Controlled component means that whenever the state of the form changes, it will be written into the state of the component. This kind of component is called a controlled component

Ordinary components cannot change the value of the input box, then combine the input component and state and then bind the onChange event, and finally use the state to update the value in real time and display it in the input, thus forming a controlled component

In our example, a radio button of the input type is radio. Different speeds are set and specified according to the selected item. At the same time, the selected state of the radio button is updated in real time according to the different speeds, thus forming a controlled Components

//duration is state

<label><input type="radio" name="time" value="0.13" onChange={this.handledurationChange} checked={(this.state.duration == "0.13") ? "checked" : ""}/>快</label>
<label><input type="radio" name="time" value="0.55" onChange={this.handledurationChange} checked={(this.state.duration == "0.55") ? "checked" : ""}/>正常</label>
<label><input type="radio" name="time" value="1" onChange={this.handledurationChange} checked={(this.state.duration == "1") ? "checked" : ""}/>慢</label>
handledurationChange = (event) =>{
this.setState({
duration: event.target.value
})
//此处打印的结果是上一次的duration,因为react会把传进来的state缓存起来,稍后再更新到state上
//因此,如果要在此处使用duration进行运算的话需要另想办法
console.log("duration2:"+ this.state.duration);
}

In this way, users can click different radio buttons to select different radio buttons, but the printed duration result is not the updated value we expect, but the last value. Because React will cache the incoming state, put this object into an update queue, and later will extract the new state from the queue and merge it into the state, and then trigger component updates.

Although the value obtained at this moment is not the value of the final duration, after testing, when the duration is used in other methods, its value has been updated and can be used normally!

In addition, if you want to use the new duration value for calculation at this moment, you can lead to another use of setstate, which is to receive a function as a parameter

handledurationChangeTest = (event) =>{
this.setState((prevState) => {
return{duration:0}
})
this.setState((prevState) => {
return{duration: prevState.duration+1}
})
console.log("duration2:"+ this.state.duration);
}

The test code can normally display the change of duration, indicating that the method of using functions to pass parameters is feasible!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_37719279/article/details/101550760