【发布时间】:2018-08-17 03:51:24
【问题描述】:
好的,我会尽快解决这个问题,因为它应该很容易解决...
我读过很多类似的问题,答案似乎很明显。我一开始就不需要查找任何东西!但是...我遇到了一个错误,我无法理解如何解决或为什么会发生。
如下:
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 时也是如此;如果它开始为假,那么在我第一次点击时它仍然是假的,即使复选框是否被选中是基于状态的!!
这是一个疯狂的悖论,我不知道发生了什么,请帮忙!
【问题讨论】:
标签: javascript html reactjs event-handling