gpt4 book ai didi

javascript - 如何在 onClick 事件(ReactJS)之后停止 onMouseOut 事件?

转载 作者:行者123 更新时间:2023-11-30 14:51:17 29 4
gpt4 key购买 nike

当悬停在相邻文本上时,我需要使隐藏按钮可见。这是通过 onMouseEnteronMouseLeave 事件完成的。但是当点击另外的文本时,我需要使按钮完全可见并停止 onMouseLeave 事件

到目前为止,我已经尝试过:尝试使用 removeEventListener 删除 onMouseLeave 事件。

我知道我们可以借助像这样的变量来做到这一点:

const mouseOut = (divId) => {
if (!wasClicked)
document.getElementById(divId).style.visibility = "hidden";
}

但由于我有太多不同的按钮和文本,我也不想使用变量。

<div className="step-buttons" onMouseEnter={mouseOver.bind(this, 'feature')}
onMouseLeave={mouseOut.bind(this, 'feature')}
onClick={showButtonOnClick.bind(this, 'feature')}>Test Suite
</div>

有什么可以帮助我的吗?

任何建议都会很受欢迎,提前致谢:)

最佳答案

方式一:您可以在 MouseEnter 函数中安装一个用于离开的事件监听器,并使用 refs 在 onClick 事件处理中将其删除,如下所示:

constructor(props) {
super(props);
this.text;
this.onMouseLeave = this.onMouseLeave.bind(this);
}

onMouseEnter(){
//apply your styles
this.text.addEventListener('mouseleave', this.onMouseLeave);
}

onMouseLeave(){
//remove your styles
}

showButtonOnClick(){
//remove the eventlistener
this.text.removeEventListener('mouseleave', this.onMouseLeave);
}

render(){
return(
<div ref={(thiscomponent) => {this.text = thiscomponent}}
onMouseEnter={this.onMouseEnter.bind(this, 'feature')}
onClick={this.showButtonOnClick.bind(this, 'feature')}>
Test Suite
</div>);
}

ref 只是对您的 div 的引用,因此您可以将事件监听器挂载到它。您必须在构造函数中绑定(bind)该函数,因为 .bind(this) 将在您调用它时创建一个新函数,以防止多次安装事件处理程序。

方法 2(可能更好):另一种方法是保存对状态中文本的点击,并根据此有条件地更改 onMouseLeave 函数的作用:

constructor(props) {
super(props);
this.state={
clicked: false,
}
}

onMouseEnter(){
//apply your styles
}

onMouseLeave(){
if(!this.state.clicked){
//remove styles
}
}

showButtonOnClick(){
this.setState({clicked: true});
}

render(){
return(
<div
onMouseEnter={this.onMouseEnter.bind(this)}
onMouseLeave={this.onMouseLeave.bind(this)}
onClick={this.showButtonOnClick.bind(this)}>
Test Suite
</div>);
}

关于javascript - 如何在 onClick 事件(ReactJS)之后停止 onMouseOut 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48060660/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com