How do you set the value attribute in a React page?
In a React page, the value attribute can be set using the following method:
- Utilize controlled components: By binding the value attribute and onChange event handling function to the value in the state, controlled input fields can be achieved. In the render function, pass the value from the state as the value attribute for the input field.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
}
handleChange(event) {
this.setState({ value: event.target.value });
}
render() {
return (
<input
type="text"
value={this.state.value}
onChange={this.handleChange.bind(this)}
/>
);
}
}
- If you do not want to bind the value of the input box to state, you can use the defaultValue attribute to set the default value of the input box. In the render function, pass the default value as the value of the defaultValue attribute to the input box.
class MyComponent extends React.Component {
render() {
return (
<input
type="text"
defaultValue="默认值"
/>
);
}
}
It is important to note that when using controlled components to set the value attribute, the state value needs to be updated in the onChange event handler. On the other hand, if using the defaultValue attribute, the input field value will not change as the user inputs unless the defaultValue value is manually modified.