Two-way data binding is very convenient in VUE. How to implement a simple two-way data binding in React?
React implements a simple two-way binding
First we add an onChange event to the input and then bind the value of the input field to state
<Input placeholder=" placeholder "onChange={this.productname.bind (this)} value={this.state.inpvalu}/>Copy the code
constructor(props) {
super(props)
this.state = {
inpValu:""
}
}
Copy the code
The onChange event is triggered when the value of the input is changed, and returns the value of the target value that is the current value of the input. In this case, we only need to set the value to the value binding of the input in state.
ProductName(e){
this.setState({
inpValu:e.target.value
})
}
Copy the code
This allows the value of the input to change and the value of the state to change. The value of state changes, and the value of input changes as well, a simple two-way data binding.
It is important to note that setState is asynchronous when it is used to change the value of state. To retrieve the value as it is set, you need to pass a callback function in its second argument that can retrieve the modified value
chongZhi (){ this.setState({ProductName:""},function () { console.log(this.state.ProductName); })}Copy the code
Encapsulated event handling
If a page has too many form elements, write a change for each event handler, repeat too much code, you will find different elements, event handlers, but setState corresponding to the key name, can consider encapsulation? Use a single event handler to pass in different values.
constructor(){
super()
this.changeHandle = this.changeHandle.bind(this);
this.state={
name:"",
pwd:"",
email:""
}
}
Copy the code
render(){
let {name,pwd,email} = this.state;
return (
<div>
<input data-key="name" onChange={this.changeHandle} value={name} type="text" />
<input data-key="pwd" onChange={this.changeHandle} value={pwd} type="text" />
<input data-key="email" onChange={this.changeHandle } value={email} type="text"/>
<span>name:{name}</span>
<span>pwd:{pwd}</span>
<span>email:{email}</span>
</div>
)
}
Copy the code
changeHandle(e){
e.preventDefault()
let key = e.target.dataset.key;
this.setState({[key]:e.target.value})
}
Copy the code
For more articles, please pay attention to bug Collection or bug Collection