React 的 useOnGlobalEvent 钩子

ReactReactBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索 React 中的 useOnGlobalEvent 钩子。这个钩子使我们能够监听在全局对象上发生的事件,比如 window 对象上的 mousemove 事件。通过使用这个钩子,我们可以在特定的全局事件发生时轻松地执行一个回调函数。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("React")) -.-> react/FundamentalsGroup(["Fundamentals"]) react(("React")) -.-> react/AdvancedConceptsGroup(["Advanced Concepts"]) react/FundamentalsGroup -.-> react/jsx("JSX") react/AdvancedConceptsGroup -.-> react/hooks("React Hooks") subgraph Lab Skills react/jsx -.-> lab-38399{{"React 的 useOnGlobalEvent 钩子"}} react/hooks -.-> lab-38399{{"React 的 useOnGlobalEvent 钩子"}} end

React 的 useOnGlobalEvent 钩子

虚拟机中已经提供了 index.htmlscript.js。一般来说,你只需要在 script.jsstyle.css 中添加代码。

这个函数会在全局对象上发生事件时执行一个回调函数。要实现这个函数:

  1. 使用 useRef() 钩子创建一个变量 listener,它将保存监听器引用。
  2. 使用 useRef() 钩子创建一个变量,用于保存 typeoptions 参数的前一个值。
  3. 使用 useEffect() 钩子和 EventTarget.addEventListener()Window 全局对象上监听给定的事件 type
  4. 使用 EventTarget.removeEventListener() 移除任何现有的监听器,并在组件卸载时进行清理。
const useOnGlobalEvent = (type, callback, options) => {
  const listener = React.useRef(null);
  const previousProps = React.useRef({ type, options });

  React.useEffect(() => {
    const { type: previousType, options: previousOptions } =
      previousProps.current;

    if (listener.current) {
      window.removeEventListener(
        previousType,
        listener.current,
        previousOptions
      );
    }

    listener.current = callback;
    window.addEventListener(type, callback, options);
    previousProps.current = { type, options };

    return () => {
      window.removeEventListener(type, listener.current, options);
    };
  }, [callback, type, options]);
};

以下是如何使用这个函数的示例:

const App = () => {
  useOnGlobalEvent("mousemove", (e) => {
    console.log(`(${e.x}, ${e.y})`);
  });

  return <p>Move your mouse around</p>;
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);

请点击右下角的“Go Live”以在端口 8080 上运行网络服务。然后,你可以刷新“Web 8080”标签页来预览网页。

总结

恭喜你!你已经完成了 React 的 useOnGlobalEvent 钩子实验。你可以在 LabEx 中练习更多实验来提升你的技能。