【问题标题】:Remove passive event handler for `wheel` & `scroll` events删除 `wheel` 和 `scroll` 事件的被动事件处理程序
【发布时间】:2022-07-05 17:10:29
【问题描述】:

我在尝试控制 scrollwheel 事件时遇到问题。

目前,我可以通过将事件侦听器添加到 window 对象来阻止这些特定事件,但它们的处理程序需要停用 passive 才能工作。这在尝试删除它们时会导致问题,因为“删除”事件处理程序上似乎不存在passive,并且浏览器似乎没有删除正确的事件处理程序。 Here's a link to a reproducible example 以及我在下面使用的钩子的代码

有人对此有什么好的解决方案或解决方法吗?大多数相关问题似乎没有很好(或当前)的答案来处理最近的浏览器更新以允许被动事件

const useControlScrolling = (pauseScroll: boolean): void => {
  useEffect(() => {
    const preventScroll = (e: Event) => {
      e.preventDefault();
    };
    const eventOpts = {
      passive: false
    };
    const disableScrolling = () => {
      console.log("disabling scroll");

      // I add the passive prop to the allow `preventDefault` to work
      window.addEventListener("wheel", preventScroll, eventOpts); 
      window.addEventListener("scroll", preventScroll, eventOpts); 
    };

    const enableScrolling = () => {
      console.log("enabling scroll");

      // the remove handler doesn't allow the eventOpts so it doesn't know which handler to remove. Casting it does not help
      window.removeEventListener("wheel", preventScroll); 
      window.removeEventListener("scroll", preventScroll);
    };

    if (pauseScroll) {
      disableScrolling();
    } else {
      enableScrolling();
    }
  }, [pauseScroll]);
};

export default function App() {
  const [visible, setVisible] = useState(false);
  useControlScroll(visible);

  window.addEventListener("click", () => setVisible(!visible));

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

【问题讨论】:

    标签: reactjs typescript events


    【解决方案1】:

    每次调用useControlScrolling 时,它都会创建一个新的preventScroll 函数,具有相同的代码和名称。但是,它与以前创建的功能不同。因此,当您将preventScroll 传递给removeEventListener 时,它不会找到完全相同的功能。所以该功能不会被删除。

    为了完成这项工作,您可以将preventScroll 移出useControlScrolling 以使其在每个函数调用中保持一致。

    【讨论】:

      猜你喜欢
      • 2010-11-21
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多