[英]react bind to checkbox and update state base on checked
Try to check the checkbox, you will see undefined. 尝试选中该复选框,您将看到未定义。 That's strange I think I used find
properly. 我认为我经常使用find
真是奇怪。 Or there's a better way to do it? 还是有更好的方法呢?
http://jsbin.com/ficijuwexa/1/edit?js,console,output http://jsbin.com/ficijuwexa/1/edit?js,console,output
class HelloWorldComponent extends React.Component {
constructor(){
super()
this.handleChange = this.handleChange.bind(this);
this.state = {
"fruits":[
{"name":"banana","value":true},
{"name":"watermelon","value":false},
{"name":"lemon","value":true},
]
}
}
handleChange(e,key){
const newFruitsData = this.state.fruits.find(obj => {
obj.name === key ? obj.value = e.target.checked : ''
});
console.log(newFruitsData) // <-- why does this output undefined?
}
render() {
return (
<div>
{this.state.fruits.map(obj =>
<div key={obj.name}>
<label>{obj.name}</label>
<input onChange={(e) => this.handleChange(e, obj.name)} type="checkbox" defaultChecked={obj.value} />
</div>
)}
<br />
<pre>{JSON.stringify(this.state.fruits,null,2)}</pre>
</div>
);
}
}
您的发现没有return语句,它总是返回undefined,而应该返回boolean
const newFruitsData = this.state.fruits.find(obj => obj.name === key && obj.value === e.target.checked);
In the handleChange(), the Array.prototype.find should return Bool: 在handleChange()中,Array.prototype.find应该返回Bool:
handleChange(e,key){
let nxState = Object.assign({}, this.state)
nxState.fruits.find(obj => {
if (obj.name === key) {
obj.value = e.target.checked
return true
} else {
return false
}
});
this.setState(nxState)
}
And you should use setState()
instead, it's my opinion of course 而且您应该使用setState()
,这当然是我的意见
--- Update -更新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.