[英]ReactJS: Single onChange handler for multiple form inputs
I have a form with text and number input types. 我有一个带有文本和数字输入类型的表单。 In my react app, I maintain a nested object
formInput
in the component state with all the form field values: 在我的react应用程序中,我在组件状态下使用所有表单字段值维护一个嵌套对象
formInput
:
this.state = {
// Other state variables
formInput: {
name1:'',
name2:'',
numberInput1:0,
numberInput2:0
}
}
I am very new to React and in my app, I currently have a handleOnChange()
method for each input which is a really crude way of doing it. 我对React很
handleOnChange()
,在我的应用程序中,我目前对每个输入都有一个handleOnChange()
方法,这是一种非常粗糙的方法。 Is there a way to write a single handleOnChange()
function that will update my components state when an input is changed? 有没有一种方法可以编写一个
handleOnChange()
函数,该函数在输入更改时会更新我的组件状态?
I tried this: 我尝试了这个:
handleOnChange(evt) {
this.setState({[evt.target.name]: evt.target.value});
}
But this method works if the form input fields aren't nested inside the formInput
object of my components state
. 但是如果表单输入字段没有嵌套在我组件
state
的formInput
对象内,这个方法就可行。 Is there a different way to have a single onChange
handler for fields within an object? 是否有其他方法可以为对象内的字段提供单个
onChange
处理程序?
You could adapt your handleOnChange()
method to work with nested formInput
by doing something like this: 您可以通过执行以下操作来使
handleOnChange()
方法适应嵌套的formInput
:
handleOnChange(evt) {
/* Pass callback to setState instead (optional) */
this.setState(({ formInput }) => {
/* Compose next state object, with nested formInput
describing the updated value state of the form */
const nextState = {
formInput : {
...formInput,
[evt.target.name]: evt.target.value
}
}
return nextState;
});
}
If spread syntax is not available due to your build configuration or target browser, a "non-spread" equivalent can be implemented with Object.assing()
like this: 如果由于构建配置或目标浏览器而无法使用扩展语法,则可以使用
Object.assing()
来实现“非扩展”等效项,如下所示:
handleOnChange(evt) {
/* Extract name and value from event target */
const { name, value } = evt.target;
this.setState(({ formInput }) => {
const nextState = {
/* Use Object.assign() as alternate to ... syntax */
formInput : Object.assign({}, formInput, { [name]: value })
}
return nextState;
});
}
Yes you can do that, you can use something like: 是的,您可以这样做,可以使用类似以下内容的方法:
handleOnChange(evt) {
this.setState(prevState => ({
formInput: {
...prevState.formInput,
[evt.target.name]: evt.target.value
}
}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.