admin管理员组文章数量:1410712
I have this ponent state
this.state = {
title: "",
salary: {
min: "",
max: "",
single: ""
}
}
I use this function for handling user input
handleInputChange = (e) => {
this.setState({[e.target.name]:e.target.value});
}
it works with
<input type="text" id="title" name="title" onChange={this.handleInputChange}/>
Can I use such a function to change this.state.salary.min/max ...
I mean can this type of function work with nested objects in state and <input/> name art
?
I have this ponent state
this.state = {
title: "",
salary: {
min: "",
max: "",
single: ""
}
}
I use this function for handling user input
handleInputChange = (e) => {
this.setState({[e.target.name]:e.target.value});
}
it works with
<input type="text" id="title" name="title" onChange={this.handleInputChange}/>
Can I use such a function to change this.state.salary.min/max ...
I mean can this type of function work with nested objects in state and <input/> name art
?
- You're gonna have to give us a little more info, and maybe format the question a little better. What exactly isn't working? Could you provide an example? – ZekeDroid Commented Feb 7, 2018 at 19:00
-
i have state prop called
title
i use this function and chnage the state based on the name of the input field and its value , my question is ... can this type of logic work for nested objects in state (e.g. salary.min) – Георги Димитранов Commented Feb 7, 2018 at 19:02
2 Answers
Reset to default 4Yes you can, but you need to update whole nested object.
You have several options:
Object.assign()
const salary = Object.assign({}, this.state.salary, { min: minValue });
this.setState({ salary });
Spread operator
const salary = {
...this.state.salary,
min: minValue
}
this.setState({ salary });
Immutable data structure
Immutable.js
this.state = {
salary = Immutable.Map({
min: 8,
max: 10
});
};
const salary = this.state.salary.set('min', minValue);
this.setState({ salary });
Immutability helper
See https://reactjs/docs/update.html
const salary = update(this.state.salary, {
min: minValue
});
this.setState({ salary });
Yes, you can do that by using spread operator in setState.
this.setState(prevState => ({
...prevState,
salary: {
...prevState.salary,
min: newMinValue
}
}))
Or, you can use Object.assign() if you are using ES5.
this.setState({
salary: Object.assign({}, this.state.salary, {min: newMinValue})
});
本文标签: javascriptChange state of nested object props based on user input handleChangeStack Overflow
版权声明:本文标题:javascript - Change state of nested object props based on user input handleChange - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744909196a2631809.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论