Reactjs setState() with a dynamic key name?

2019-01-04 06:40发布

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?

6条回答
Lonely孤独者°
2楼-- · 2019-01-04 06:52

In loop with .map work like this:

{
    dataForm.map(({ id, placeholder, type }) => {
        return <Input
            value={this.state.type}
            onChangeText={(text) => this.setState({ [type]: text })}
            placeholder={placeholder}
            key={id} />
    })
}

Note the [] in type parameter. Hope this helps :)

查看更多
贪生不怕死
3楼-- · 2019-01-04 06:55

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

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 });
}
查看更多
做自己的国王
4楼-- · 2019-01-04 07:02

Can use a spread syntax, something like this:

inputChangeHandler : function (event) {
    this.setState( { 
        ...this.state,
        [event.target.id]: event.target.value
    } );
},
查看更多
冷血范
5楼-- · 2019-01-04 07:05

Just wanted to add, that you can also de-structuring to refactor the code and make it look neater.

inputChangeHandler: function ({ target: { id, value }) {
    this.setState({ [id]: value });
},
查看更多
劫难
6楼-- · 2019-01-04 07:11

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.

For example:

inputChangeHandler(event) {
  this.setState({ [event.target.name]: event.target.value });
}

查看更多
成全新的幸福
7楼-- · 2019-01-04 07:13

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)
},
查看更多
登录 后发表回答