【发布时间】:2015-10-24 20:17:16
【问题描述】:
我正在尝试实现悬停事件,但在离开元素时并不总是触发 onMouseLeave,尤其是在将光标快速移动到元素上时。我尝试了 Chrome、Firefox 和 Internet Explorer,但在每个浏览器中都出现了同样的问题。
我的代码:
import React from 'react';
import Autolinker from 'autolinker';
import DateTime from './DateTime.jsx'
class Comment extends React.Component{
constructor(props){
super(props);
this.handleOnMouseOver = this.handleOnMouseOver.bind(this);
this.handleOnMouseOut = this.handleOnMouseOut.bind(this);
this.state = {
hovering: false
};
}
render(){
return <li className="media comment" onMouseEnter={this.handleOnMouseOver} onMouseLeave={this.handleOnMouseOut}>
<div className="image">
<img src={this.props.activity.user.avatar.small_url} width="42" height="42" />
</div>
<div className="body">
{this.state.hovering ? null : <time className="pull-right"><DateTime timeInMiliseconds={this.props.activity.published_at} byDay={true}/></time>}
<p>
<strong>
<span>{this.props.activity.user.full_name}</span>
{this.state.hovering ? <span className="edit-comment">Edit</span> : null}
</strong>
</p>
</div>
</li>;
}
handleOnMouseOver(event){
event.preventDefault();
this.setState({hovering:true});
}
handleOnMouseOut(event){
event.preventDefault();
this.setState({hovering:false});
}
newlines(text) {
if (text)
return text.replace(/\n/g, '<br />');
}
}
export default Comment;
【问题讨论】:
-
你好,你怎么确定onMouseLeave没有被触发?您是否尝试过添加 console.log 语句?我想知道您是否遇到了 onMouseOver/onMouseOut 的错误排序,因为状态设置不是同步操作。我创建了一个简单的 React 组件,但无法轻松重现。
-
有时会发生,当离开元素时没有调用 onMouseLeave 函数。是的,我尝试使用日志记录并且没有调用函数。那么我应该如何实现悬停事件?
-
您可以尝试 onMouseOver/onMouseOut 看看它是否更适合您,因为我认为这些事件得到了更好的支持,尽管其行为略有不同,因此可能不适合您的应用程序。
-
请上传 JSFiddle 以了解您的问题。我在您的代码中找不到任何错误。此外,不鼓励使用 mouseout,因为当有子元素时,它的工作方式会有所不同。您可以在 jQuery 的文档中看到差异(虽然您没有使用 jQuery,但行为基本相同):api.jquery.com/mouseleave
-
@Alexandr 你能提供更多信息吗?谢谢
标签: javascript events hover reactjs eventtrigger