如何使用钩子通过一个事件处理函数动态更新任何输入字段的值 [英] How to dynamically update the value for any input field with one event handler function, using hooks
问题描述
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 更新状态时,两个状态都会更新.这不是本意.
I am working on a login form with 2 fields. Email and Password. When i am using 2 useState representing the two field, then when i update the state with handleChange both state get updated. Which is not the intention.
const [email, setEmail] = useState()
const [password, setPassword] = useState()
const handleChange = e => {
const {value} = e.target
setEmail(value)
setPassword(value)
}
我不想使用多个事件处理程序来处理每个输入字段.我试过这个
I don't want to use multiple event handler for handling each input field. I tried this
const [state , setState] = useState({
email : "",
password : ""
})
const handleChange = e => {
const {name , value} = e.target
setState({
[name] : value
})
}
但这一次更新一个属性.并且其他财产价值丢失.那么有没有什么方法可以像我们使用有状态组件那样使用一个事件处理函数来更新我的所有输入字段.
But this updates one property at a time. And the other property value get lost. So is there any way that i can update all my input fields with one event handler function like we could do with stateful component.
this.state = {
email : "",
password : ""
}
const handleChange = e => {
const {name , value} = e.target
this.setState({
[name] : value
})
}
推荐答案
你应该使用 setState 和回调函数:
You should use setState with callback function:
setState(prev => ({
...prev,
email: 'new mail',
}))
您将创建一个新的 state 对象,该对象由以前的 state 创建.你可以覆盖任何你需要的东西.如果您有一个复杂的状态对象,则需要更多的新对象.
You'll create a new state object, which was created by previous state. And you can override anything you need. You'd need more new objects if you'd have a complex state object.
这篇关于如何使用钩子通过一个事件处理函数动态更新任何输入字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!