【问题标题】:React onMouseEnter not firing in Chrome when element blocking cursor disappears当元素阻止光标消失时,React onMouseEnter 不会在 Chrome 中触发
【发布时间】:2019-09-14 03:37:00
【问题描述】:

注意:这似乎是 Chrome 独有的问题

当阻止事件元素的元素消失时,React 当前不会触发 onMouseEnter 事件。标准 JS 事件甚至委托事件都不是这种情况。

这是我遇到的问题的简化描述和代码示例;当来自下部元素的工具提示消失(并且光标位于上部元素上方)时,onMouseEvent 不会触发:

function reactMouseEnter({currentTarget}) {
  console.log('React Mouse Enter Event');
  const rect = currentTarget.getBoundingClientRect();
  const tooltip = document.createElement('div');
  tooltip.classList.add('tooltip');
  tooltip.style.top = rect.y - 30 + 'px';
  document.body.appendChild(tooltip);

  const mouseLeaveHandler = () => {
    currentTarget.removeEventListener('mouseleave', mouseLeaveHandler);
    setTimeout(() => {
      tooltip.parentNode.removeChild(tooltip);
    }, 300);
  };

  currentTarget.addEventListener('mouseleave', mouseLeaveHandler);
}

class Example extends React.Component {
  ref = React.createRef()
  componentDidMount() {
    this.ref.current.addEventListener('mouseenter', () => {
      console.log('Regular Mouse Enter Event');
    })
  }
  render() {
    return (
      <div>
        <div onMouseEnter={ reactMouseEnter } ref={this.ref} className="box" />
        <div onMouseEnter={ reactMouseEnter } className="box" />
      </div>
    );
  }
}

ReactDOM.render(<Example /> , document.getElementById('example'));
.box {
  border: 1px solid black;
  height: 28px;
  margin-bottom: 10px;
  position: relative;
  width: 28px;
}

.tooltip {
  width: 30px;
  height: 30px;
  background-color: lightcoral;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.2/umd/react-dom.production.min.js"></script>

<div id="example" style="margin-top: 30px;"></div>

我可以在 React 中做些不同的事情来让 onMouseEnter 工作吗?我也尝试改用onMouseOver,但它在我的实际实现中会产生其他意想不到的副作用,所以我更愿意看看onMouseEnter是否可行。

【问题讨论】:

    标签: javascript reactjs google-chrome


    【解决方案1】:

    这在技术上是有意的,因为 onMouseEnter 只在元素的边框上触发。你想使用 onMouseOver。

    你可以看到这个demo comparison here,带有计数器的中心框不是元素的一部分,所以用它来测试。

    【讨论】:

    • 我更新了我的问题,以更好地反映标准 JavaScript 事件仍然被触发,即使手头存在问题。如果你重新运行我上面的例子,你会看到常规事件被触发,而反应事件没有。
    • @KevBot 只需将您的onMouseEnters 更改为onMouseOver。为我工作。
    • @KevBot 你将无法让它与 onMouseEnter 一起工作,但如果你让我们知道意外的一面会影响你所面临的问题,我可以尝试提供帮助。您可以随时向 onMouseOver 添加条件检查。
    猜你喜欢
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    相关资源
    最近更新 更多