TL;DR
Is there any way to dynamically update the value for input fields with one event handler function like we could do with stateful component.
我正在制作一个包含 2 个字段的登录表单。电子邮件和密码。当我使用 2 个 useState 代表两个字段时,当我使用 handleChange 更新状态时,两个状态都会更新。这不是本意。
const [email, setEmail] = useState()
const [password, setPassword] = useState()
const handleChange = e => {
const {value} = e.target
setEmail(value)
setPassword(value)
}
我不想使用多个事件处理程序来处理每个输入字段。我试过这个
const [state , setState] = useState({
email : "",
password : ""
})
const handleChange = e => {
const {name , value} = e.target
setState({
[name] : value
})
}
但这一次会更新一个属性。而其他属性(property)值(value)就会消失。那么有没有一种方法可以让我使用一个事件处理函数来更新所有输入字段,就像我们使用有状态组件一样。
this.state = {
email : "",
password : ""
}
const handleChange = e => {
const {name , value} = e.target
this.setState({
[name] : value
})
}
最佳答案
感谢多甘坎·阿拉巴奇。我尝试模仿基于类的组件的状态和 setState,这样感觉就不会改变。我的解决方案看起来像这样。
const [state , setState] = useState({
email : "",
password : ""
})
const handleChange = e => {
const {name , value} = e.target
setState( prevState => ({
...prevState,
[name] : value
}))
}
关于reactjs - 如何使用钩子(Hook)通过一个事件处理函数动态更新任何输入字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55923610/