在 React 中检测鼠标点击并更改状态
Detect mouse click and change state in React
我有一个 div,它根据变量显示 - 例如:showDiv
。在我设置 showDiv= true 之后,div 会出现。
{showDiv && <div id="someid"> text</div>}
已设置超时以更改变量值,以便 div 会在一段时间(7 秒)后消失
thisState.setState({showDiv:true});
setTimeout(function(){
thisState.setState({false});
}.bind(this),7000);
我如何添加代码来检测任何鼠标点击并根据它更改变量?要求是,div 也应该消失
1. 7秒后(已经完成)
2. 基于点击事件(如果用户只是点击屏幕)
有什么想法吗?
您本质上是在寻找 window 事件侦听器。
componentDidMount(){
window.addEventListener("click", this.hideDiv)
}
hideDiv = () => {
if(this.state.showDiv){
this.setState({
showDiv: false
})
}
}
还记得在卸载组件之前删除该侦听器:
componentWillUnmount{
window.removeEventListener("click", this.hideDiv)
}
我有一个 div,它根据变量显示 - 例如:showDiv
。在我设置 showDiv= true 之后,div 会出现。
{showDiv && <div id="someid"> text</div>}
已设置超时以更改变量值,以便 div 会在一段时间(7 秒)后消失
thisState.setState({showDiv:true});
setTimeout(function(){
thisState.setState({false});
}.bind(this),7000);
我如何添加代码来检测任何鼠标点击并根据它更改变量?要求是,div 也应该消失 1. 7秒后(已经完成) 2. 基于点击事件(如果用户只是点击屏幕)
有什么想法吗?
您本质上是在寻找 window 事件侦听器。
componentDidMount(){
window.addEventListener("click", this.hideDiv)
}
hideDiv = () => {
if(this.state.showDiv){
this.setState({
showDiv: false
})
}
}
还记得在卸载组件之前删除该侦听器:
componentWillUnmount{
window.removeEventListener("click", this.hideDiv)
}