如何创建一个可重用的函数来为变量对象 属性 设置状态?
How can I create a reusable function that will setState for a variable object property?
我有一个 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 很陌生。谢谢。
你差不多明白了。只需删除 [index]
和 [e.target.name]
之间的 .
,例如:
currentStateObject[index][e.target.name] = e.target.value;
您可以简单地:
onChangeHandler(event) {
this.setState({ [event.target.name]: event.target.value })
}
这里是状态操纵的一些例子
state = {
random: [],
counter: 1
}
stateHandler = (e)=>{
let oldrandom = [...this.state.random]
oldrandom[e.target.name] = e.target.value;
this.setState({random:oldrandom })
}
manipulate state with a functional approach
stateHandler = ()=>{
this.setState((state,props)=>{
counter: state.counter+props.increment
})
}
我有一个 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 很陌生。谢谢。
你差不多明白了。只需删除 [index]
和 [e.target.name]
之间的 .
,例如:
currentStateObject[index][e.target.name] = e.target.value;
您可以简单地:
onChangeHandler(event) {
this.setState({ [event.target.name]: event.target.value })
}
这里是状态操纵的一些例子
state = {
random: [],
counter: 1
}
stateHandler = (e)=>{
let oldrandom = [...this.state.random]
oldrandom[e.target.name] = e.target.value;
this.setState({random:oldrandom })
}
manipulate state with a functional approach
stateHandler = ()=>{
this.setState((state,props)=>{
counter: state.counter+props.increment
})
}