The form
In React, mutable state is usually stored in the component’s state property and can only be updated by using setState(). Form elements typically maintain state themselves, calling the setState method to update data based on user input or click behavior.
React’s state becomes the “unique data source.” The React component that renders the form also controls what happens to the form during user input. The form input elements that React controls their values in this way are called “controlled components.”
export class NameForm extends Component { constructor(props){ super(props); this.state = {value: ''} } handleChangeEvent = (event) => { this.setState({ value: event.target.value }) } handleSubmitEvent = (event) => { console.log(this.state.value); event.preventDefault(); } render(){ return ( <form onSubmit={this.handleSubmitEvent}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChangeEvent}/> </label> <input type='submit' Value ='submit'/> </form>)}} // use setState to update the value and ensure that state is the only data sourceCopy the code
Define select as a controlled component in the same way:
export class FlavorForm extends Component {
constructor(props){
super(props);
this.state = {value: 'coconut'}
}
handleChangeEvent =(e)=>{
this.setState({
value: e.target.value
})
}
handleSubmitEvent = (e) => {
console.log(this.state.value);
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmitEvent}>
<label>
Please Select:
<select value={this.state.value} onChange={this.handleChangeEvent}>
<option value='grapefruit'>Grapefruit</option>
<option value='lime'>Lime</option>
<option value='coconut'>Coconut</option>
<option value='mango'>Mango</option>
</select>
</label>
<input type='submit' value='submit'/>
</form>
)
}
}
Copy the code
When we need to process multiple input elements, we can add a name attribute to each element and let the handler select the action to perform based on the value of event.target.name.
State of ascension
When two same-level components need to communicate with each other, if the state information of the component is stored in the component through state, it cannot be shared between components. In this case, variable promotion is considered, that is, the state information of the two child components is promoted to the negative component, and the specific value is passed to the child component through props. Similarly, setState method is defined in the parent component through callback, so that the data source can be shared between the peer components, that is, variable promotion