Reactjs setState() 带有动态键名? [英] Reactjs setState() with a dynamic key name?

查看:30
本文介绍了Reactjs setState() 带有动态键名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是重复的,见 这里

我找不到在设置状态时使用动态键名的任何示例.这就是我想要做的:

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 } );
},

其中 event.target.id 用作要更新的状态键.这在 React 中是不可能的吗?

where event.target.id is used as the state key to be updated. Is this not possible in React?

推荐答案

感谢@Cory 的提示,我使用了这个:

Thanks to @Cory's hint, i used this:

inputChangeHandler : function (event) {
    var stateObject = function() {
      returnObj = {};
      returnObj[this.target.id] = this.target.value;
         return returnObj;
    }.bind(event)();

    this.setState( stateObject );    
},

如果使用 ES6 或 Babel 转译器 来转换您的 JSX 代码,您可以使用 计算属性名称,也是:

If using ES6 or the Babel transpiler to transform your JSX code, you can accomplish this with computed property names, too:

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 });
}

这篇关于Reactjs setState() 带有动态键名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆