[英]Dynamic update the setState (Object) in React
I have a state我有一个状态
constructor(props) {
super(props);
this.state = {
qualification: {
fieldOfStudy: "Architecture",
degree: "",
}
};
}
and I would like to update the state value dynamically on function call我想在函数调用时动态更新状态值
onChange={this.handleChangeObj("qualification")}
Here is the function I have written:这是我写的函数:
handleChangeObj = (ObjName) => ({ target }) => {
//String Value - Qualification
console.log("handleChangeObj -> ObjName", ObjName);
//fieldOfStudy: Architecture
console.log((target.name + ":" + target.value));
// Doubt over here how to update the value for qualification.fieldOfStudy : Architecture
this.setState(() => ({
...this.state.ObjName,
[target.name]: [target.value],
}));
// this is not working.
this.setState({ [ObjName.target.name]: target.value });
};
The first parameter being passed to the outer function, so all you need to do is to reference that in bracket notation:传递给外部函数的第一个参数,因此您需要做的就是在括号中引用它:
this.setState({
[ObjName]: {
...this.state[ObjName],
[target.name]: [target.value]
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.