Javascript Reactjs setState() 带有动态键名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29280445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reactjs setState() with a dynamic key name?
提问by trad
EDIT: this is a duplicate, see here
编辑:这是重复的,见这里
I can't find any examples of using a dynamic key name when setting the state. This is what I want to do:
我找不到在设置状态时使用动态键名的任何示例。这就是我想要做的:
inputChangeHandler : function (event) {
this.setState( { event.target.id : event.target.value } );
},
where event.target.id is used as the state key to be updated. Is this not possible in React?
其中 event.target.id 用作要更新的状态键。这在 React 中是不可能的吗?
回答by trad
Thanks to @Cory's hint, i used this:
感谢@Cory 的提示,我使用了这个:
inputChangeHandler : function (event) {
var stateObject = function() {
returnObj = {};
returnObj[this.target.id] = this.target.value;
return returnObj;
}.bind(event)();
this.setState( stateObject );
},
If using ES6 or the Babel transpilerto transform your JSX code, you can accomplish this with computed property names, too:
如果使用 ES6 或Babel 转译器来转换您的 JSX 代码,您也可以使用计算属性名称来完成此操作:
inputChangeHandler : function (event) {
this.setState({ [event.target.id]: event.target.value });
// alternatively using template strings for strings
// this.setState({ [`key${event.target.id}`]: event.target.value });
}
回答by vikram jeet singh
When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
当需要处理多个受控输入元素时,可以给每个元素添加一个name属性,让处理函数根据event.target.name的值来选择要做什么。
For example:
例如:
inputChangeHandler(event) {
this.setState({ [event.target.name]: event.target.value });
}
回答by sintaxi
How I accomplished this...
我是如何做到这一点的...
inputChangeHandler: function(event) {
var key = event.target.id
var val = event.target.value
var obj = {}
obj[key] = val
this.setState(obj)
},
回答by saulable
I just wanted to add, that you can also use de-structuring to refactor the code and make it look neater.
我只是想补充一点,您还可以使用解构来重构代码并使其看起来更整洁。
inputChangeHandler: function ({ target: { id, value }) {
this.setState({ [id]: value });
},
回答by Johnatan Maciel
In loop with .mapwork like this:
循环.map工作是这样的:
{
dataForm.map(({ id, placeholder, type }) => {
return <Input
value={this.state.type}
onChangeText={(text) => this.setState({ [type]: text })}
placeholder={placeholder}
key={id} />
})
}
Note the []in typeparameter.
Hope this helps :)
注意[]intype参数。希望这可以帮助 :)
回答by Matthew Holtom
I had a similar problem.
我有一个类似的问题。
I wanted to set the state of where the 2nd level key was stored in a variable.
我想设置第二级密钥存储在变量中的状态。
e.g. this.setState({permissions[perm.code]: e.target.checked})
例如 this.setState({permissions[perm.code]: e.target.checked})
However this isn't valid syntax.
但是,这不是有效的语法。
I used the following code to achieve this:
我使用以下代码来实现这一点:
this.setState({
permissions: {
...this.state.permissions,
[perm.code]: e.target.checked
}
});
回答by Jujhar Singh
With ES6+ you can just do [${variable}]
使用 ES6+,你可以做 [ ${variable}]
回答by Catalina
I was looking for a pretty and simple solution and I found this:
我一直在寻找一个漂亮而简单的解决方案,我发现了这个:
this.setState({ [`image${i}`]: image })
Hope this helps
希望这可以帮助
回答by Javatar
this.setState({ [`${event.target.id}`]: event.target.value}, () => {
console.log("State updated: ", JSON.stringify(this.state[event.target.id]));
});
Please mind the quote character.
请注意引号字符。
回答by manoj patel
Your state with dictionary update some key without losing other value
你的字典状态更新一些键而不会丢失其他值
state =
{
name:"mjpatel"
parsedFilter:
{
page:2,
perPage:4,
totalPages: 50,
}
}
Solution is below
解决方法如下
let { parsedFilter } = this.state
this.setState({
parsedFilter: {
...this.state.parsedFilter,
page: 5
}
});
here update value for key "page" with value 5
这里更新值为 5 的键“页面”的值

