问题
in react.js i add a name attribute to each element For example:
handleChange1(event) {
const {name, value} = event.target
this.setState({[name]: value});
}
<input name="inputone" type="text" value={this.state.value1} onChange={this.handleChange1} />
But how do I do that in react-hook? for example:
<Input
name="FirstName"
onChange={onChangeFirstName}
></Input>
const onChangeFirstName = (event) => {
setFirstName(event.target.value);
};
In fact, my question is, if I have multiple inputs, how can I write a handleChange for them?
回答1:
I did ask similar question a month ago, about using hooks with multiple state, with one onChangeHandler using hooks:
const [name, setName] = useState({
firstName: '',
middleName: '',
lastName: '',
})
const onChangeHandler = (event) => {
const {name, value} = event.target;
setName({
...name,
[name]: value,
})
}
return(
<div>
<input
type="text"
name="fistName"
value={firstNmae}
onChange={onChangeHandler}
/>
</div>
)
来源:https://stackoverflow.com/questions/64413135/how-can-i-have-only-one-onchange-for-several-inputs-in-reacthooks