This is the fourth day of my participation in Gwen Challenge
Uncontrolled component
Uncontrolled input is similar to a traditional form input:
class Form extends Component {
render() {
return (
<div>
<input type="text" />
</div>); }}Copy the code
It records your input, and then you can retrieve the recorded input via ref, for example:
class Form extends Component {
handleSubmitClick = () = > {
const name = this._name.value;
// do something with `name`
};
render() {
return (
<div>
<input type="text" ref={input= > (this._name = input)} />
<button onClick={this.handleSubmitClick}>Sign up</button>
</div>); }}Copy the code
In other words, you must get your input from the corresponding field area.
The controlled components
A controlled input takes its current value as a prop and modifies it with a callback function, much like react.
All inputs are stored in state:
class Form extends Component {
constructor() {
super(a);this.state = {
name: ""
};
}
handleNameChange = event= > {
this.setState({ name: event.target.value });
};
render() {
return (
<div>
<input
type="text"
value={this.state.name}
onChange={this.handleNameChange}
/>
</div>); }}Copy the code
This pattern pushes the value changes for each field uniformly to the form component, so the form component can always get the current value of each input without having to figure out which input changed.
This means that your inputs are always in sync with their state inputs. State controls input; input changes trigger state updates, so that inputs change immediately:
- Input verification feedback immediately
- Submit button Is disabled unless all fields are verified successfully
- Force input in a specific format
How to become a controlled component
You just need to set the value of the form element with prop. Common form elements look like this:
The element | value | The callback | Callback the value inside |
---|---|---|---|
<input type="text" /> |
value="string" |
onChange |
event.target.value |
<input type="checkbox" /> |
checked={boolean} |
onChange |
event.target.checked |
<input type="radio" /> |
checked={boolean}" |
onChange |
event.target.checked |
<textarea /> |
value="string" |
onChange |
event.target.value |
<select /> |
value="option value" |
onChange |
event.target.value |
conclusion
features | controlled | uncontrolled |
---|---|---|
Submit a check | Square root | Square root |
The real-time calibration | Square root | x |
Submit button condition disabled | Square root | x |
Mandatory input format | Square root | x |
multi-input | Square root | x |
Dynamic input | Square root | x |