You can control the values of more than one input field by adding a name attribute to each element.
When you initialize the state in the constructor, use the field names.
To access the fields in the event handler use the event.target.name and event.target.value syntax.
To update the state in the this.setState method, use square brackets [bracket notation] around the property name.
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
age: null,
};
}
myChangeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
this.setState({[nam]: val});
}
render() {
return (
<form>
<h1>Hello {this.state.username} {this.state.age}</h1>
<p>Enter your name:</p>
<input
type='text'
name='username'
onChange={this.myChangeHandler}
/>
<p>Enter your age:</p>
<input
type='text'
name='age'
onChange={this.myChangeHandler}
/>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
No comments:
Post a Comment