最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use Variables in setState in JSX - Stack Overflow

programmeradmin8浏览0评论

I would like to use a variable in the setState function in a JSX file for React.

How would I restructure this code:

var name = e.target.name;
if(name == "title"){
    this.setState({ title: e.target.value});
}
else if(name == "date"){
    this.setState({ date: e.target.value});
}
else if(name == "amount"){
    this.setState({ amount: e.target.value});
}

Into something like this (so I don't repeat myself)?

var name = e.target.name;
this.setState({ name: e.target.value});

The above syntax just sets the state of "name" and not the value of the "name" variable.

I would like to use a variable in the setState function in a JSX file for React.

How would I restructure this code:

var name = e.target.name;
if(name == "title"){
    this.setState({ title: e.target.value});
}
else if(name == "date"){
    this.setState({ date: e.target.value});
}
else if(name == "amount"){
    this.setState({ amount: e.target.value});
}

Into something like this (so I don't repeat myself)?

var name = e.target.name;
this.setState({ name: e.target.value});

The above syntax just sets the state of "name" and not the value of the "name" variable.

Share Improve this question edited Jan 30, 2016 at 11:51 Dmitry Shvedov 3,2864 gold badges40 silver badges56 bronze badges asked Jun 1, 2015 at 0:06 sifxtremesifxtreme 4255 silver badges8 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

Easy:

var newState = {};
newState[e.target.name] = e.target.value;
this.setState(newState);
var update = {};
update[e.target.name] = e.target.value;
this.setState(update);

If you're using an ES6 transpliler that supports computed property names (like Babel), you can do:

this.setState({[e.target.name]: e.target.value});
发布评论

评论列表(0)

  1. 暂无评论