将鼠标悬停在相邻文本上时,我需要显示隐藏按钮。这是通过onMouseEnter和onMouseLeave事件完成的。但是当点击文本时,我需要使按钮完全可见并停止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>
有什么东西可以帮助我吗?
任何建议都会受到欢迎,在此先感谢:)
方法1:您可以挂载一个eventlistener以便在MouseEnter函数中保留并在onClick事件处理中使用refs删除它,如下所示:
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的引用,因此您可以将eventlistener挂载到它。你必须在构造函数中绑定函数,因为.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>);
}
您可以使用removeEventListener删除showButtonOnClick函数中的mouseleave事件
showButtonOnClick(){
...your function...
document.getElementById('step-button').removeEventListener('mouseleave',this.callback());
}
callback(){
console.log("mouseleave event removed");
}
正如您多次这样做,似乎将这些作为组件创建并使用其状态来存储可见性而不创建大量的全局变量可能是值得的。