【发布时间】:2020-01-01 17:23:32
【问题描述】:
我有一个 onChange 函数来更新我所有表单输入的状态。我在这里尝试更新的状态作为对象嵌套在数组中,但我不确定如何创建一个可重用的函数,该函数将根据更改的表单输入更新特定的对象属性。
这是我的功能:
onChangeHandler = (e, index) => {
let currentStateObject = [...this.state.fundGroups]; //copying the current state
// This works, but I don't want allocationName to be hardcoded.
// How can I pass in a variable that relates to the specific property
// based on which input field is changed?
currentStateObject[index].allocationName = e.target.value;
this.setState({
currentStateObject
});
}
这是我尝试过的,但它不起作用并用无效的令牌消息破坏了我的代码:
currentStateObject[index].[e.target.name] = e.target.
我尝试这样做是因为在我的输入字段中,我添加了name="allocationName"
有谁知道我是否即将解决这个问题?我对 React 很陌生。谢谢。
【问题讨论】:
-
为什么这个问题的票数接近?
标签: javascript arrays reactjs object setstate