首页 > 解决方案 > React onWheel 处理程序无法阻止Default,因为它是一个被动事件监听器

问题描述

我正在尝试覆盖组件上的 Ctrl+scroll 行为,但它不适用于 error [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See <URL>。我想我可以使用主动监听器,那么有没有办法通过 React 来指定呢?请注意,我需要访问和修改onWheel.

  const onWheel = (e: React.WheelEvent): void => {
    if (e.altKey) {
      e.preventDefault();
      // Error
    } else if (e.ctrlKey) {
      e.preventDefault();
      // Error
    }
  };

...

  return (<div className={styles["workspace"]} onWheel={onWheel}>
    stuff
  </div>);

标签: javascriptreactjsdomdom-events

解决方案


有点晚了,但也许它可以帮助别人。

问题是React 默认使用被动事件处理程序,带有 wheel、touchstart 和 touchmove 事件——换句话说,你不能stopPropagation在它们中调用。

如果要使用非被动事件处理程序,则需要使用refs并手动添加/删除事件处理程序,如下所示:

class MyComponent extends React.Component {
  myRef = React.createRef();

  componentDidMount() {
    // IMPORTANT: notice the `passive: false` option
    this.myRef.current.addEventListener('wheel', this.handleWheel, { passive: false });
  }

  componentWillUnmount() {
    this.myRef.current.removeEventListener('wheel', this.handleWheel, { passive: false });
  }

  handleWheel = (e) => {
    e.stopPropagation();
    // ...
  }

  // ...
}

应该与钩子类似。


推荐阅读