In React, a controlled component is a component that uses state to get and set the value of an input element; it can also be understood that the React component that renders the form also controls the operations that occur on the form during the user input process, and is used by React to Form input elements that control their values in this way are called controlled components.
The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.
The React official website explains controlled components like this: The React component that renders the form also controls the operations that occur on the form during user input. Form input elements whose values are controlled by React in this way are called "controlled components".
Components that use state to get and set input element values are called controlled components. Tags such as ,
Some netizens explained this: In React, whenever the state of the form changes, it will be written to the state of the component. This type of component is called a controlled component in React.
Update process of controlled components:
1, you can set the default value of the form in the initial state
2, whenever the value of the form changes, call onChange event handler,
3, the event handler gets the changed state through the event object e, and changes the state;
4, setState triggers the view update to complete the update of the form component value
Example: input
- Prevent form submission
class NameForm extends React.Component { constructor(props) { super(props); this.state = { value: '' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({ value: event.target.value }); } handleSubmit(event) { alert('提交的名字: ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> 名字: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="提交" /> </form> ); } }
- file type input
// file类型的input,属性value是只读的,所以是非受控组件 <input type="file" />
Recommended learning: "react Video tutorial》
The above is the detailed content of What are controlled components in react. For more information, please follow other related articles on the PHP Chinese website!