我正在制作一个易于切换的组件,这里我制作了一扇门作为示例。你点击门,它会打开,如果你再次点击它,它会关闭。如果您在门外点击,它也会关闭。
我的问题是,在 handleClick()
方法中,state.active
始终是 false
,无论如何。即使在我设置状态之后,当我 console.log
时它也会返回 false。虽然实际的 door
确实获得了分配给它的 "active"
类,但为什么该方法看不到变化?
export default class Door extends React.Component {
constructor() {
super()
this.state = {
active: false,
}
this.close = this.close.bind(this)
this.open = this.open.bind(this)
}
handleClick() {
if (this.state.active == false) {
this.open()
} else {
this.close()
}
}
open() {
document.body.addEventListener('click', this.close, true)
this.setState({active: true})
}
close() {
document.body.removeEventListener('click', this.close, true)
this.setState({active: false})
}
render() {
let classes = {
active: this.state.active ? 'active ' : '',
}
return (
<div onClick={this.handleClick.bind(this)} className={"door " + classes.active}>
</div>
)
}
}
最佳答案
你应该停止传播:
handleClick(e) {
e.stopPropagation();
if (this.state.active == false) {
this.open()
} else {
this.close()
}
}
当您尝试关门时,handleClick 会被调用两次。单击一次 div,然后单击 body。这可以通过阻止事件在处理一次时冒泡来避免。
关于javascript - this.setState() 无法正常处理绑定(bind)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39374904/