好的,我会尽快讲清楚这个问题,因为这应该是一个很容易解决的问题...
我读了很多类似的问题,答案似乎很明显。在第一时间就不需要查找任何东西!但是......我遇到了一个错误,我无法理解如何修复或者为什么会发生。
具体如下:
class NightlifeTypes extends Component {
constructor(props) {
super(props);
this.state = {
barClubLounge: false,
seeTheTown: true,
eventsEntertainment: true,
familyFriendlyOnly: false
}
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange = (event) => {
if(event.target.className == "barClubLounge") {
this.setState({barClubLounge: event.target.checked});
console.log(event.target.checked)
console.log(this.state.barClubLounge)
}
}
render() {
return (
<input className="barClubLounge" type='checkbox' onChange={this.handleOnChange} checked={this.state.barClubLounge}/>
)
}
还有更多的代码包围着这里,但这就是我的问题所在。应该可以工作,对吧?
我也试过这个:
handleOnChange = (event) => {
if(event.target.className == "barClubLounge") {
this.setState({barClubLounge: !this.state.barClubLounge});
console.log(event.target.checked)
console.log(this.state.barClubLounge)
}
所以我有两个console.log()
,两者应该是相同的。我实际上将状态设置为与上面一行中的event.target.checked
相同!
但它总是返回与应该相反的结果。
当我使用!this.state.barClubLounge
时也是如此;如果它一开始为false,在我的第一次点击中它仍然为false,即使复选框是否被选中基于状态!!
这是一个疯狂的悖论,我不知道发生了什么,请帮帮我!