快速移动光标时,不会触发反应事件onMouseLeave

zaz*_*ter 23 javascript events eventtrigger hover reactjs

我试图实现悬停事件但是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;
Run Code Online (Sandbox Code Playgroud)

bzk*_*bzk 14

当事件侦听器位于父元素上并且有条件地从 DOM 中添加/删除子元素时,似乎是由事件委托引起的问题。放置一个位于所有内容之上的“悬停目标”组件应该可以正常工作,但如果您需要单击其中的元素,则可能会导致其他问题。

<Container isOpen={this.state.isOpen}>
 <HoverTarget
  onMouseEnter={e => this.mouseOver(e)}
  onMouseLeave={e => this.mouseOut(e)}
 />
 <Content/>
</Container>



mouseOver(e) {
  if (!this.state.isOpen) {
    this.setState({ isOpen: true });
  }
}
Run Code Online (Sandbox Code Playgroud)