React 的 useMutationObserver 钩子

ReactReactBeginner
立即练习

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

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

简介

在本实验中,我们将学习如何在 React 中使用 useMutationObserver 钩子,通过 MutationObserver 来监听 DOM 树的变化。该钩子允许我们指定一个在观察到变化时执行的回调函数,还可以提供选项来自定义观察者的行为。通过本实验,我们将能够理解如何在 React 应用程序中实现 useMutationObserver 钩子。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("React")) -.-> react/FundamentalsGroup(["Fundamentals"]) react(("React")) -.-> react/AdvancedConceptsGroup(["Advanced Concepts"]) react(("React")) -.-> react/StylingGroup(["Styling"]) react(("React")) -.-> react/StateManagementGroup(["State Management"]) react/FundamentalsGroup -.-> react/jsx("JSX") react/FundamentalsGroup -.-> react/event_handling("Handling Events") react/AdvancedConceptsGroup -.-> react/hooks("React Hooks") react/StylingGroup -.-> react/css_in_react("CSS in React") react/StateManagementGroup -.-> react/use_state_reducer("Using useState and useReducer") subgraph Lab Skills react/jsx -.-> lab-38397{{"React 的 useMutationObserver 钩子"}} react/event_handling -.-> lab-38397{{"React 的 useMutationObserver 钩子"}} react/hooks -.-> lab-38397{{"React 的 useMutationObserver 钩子"}} react/css_in_react -.-> lab-38397{{"React 的 useMutationObserver 钩子"}} react/use_state_reducer -.-> lab-38397{{"React 的 useMutationObserver 钩子"}} end

React 的 useMutationObserver 钩子

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

要监听对 DOM 树所做的更改,可以使用 useMutationObserver 钩子。其工作原理如下:

  1. 该钩子接受三个参数:refcallbackoptions
  2. 在钩子内部,使用了一个依赖于 callbackoptions 值的 useEffect() 钩子。
  3. 如果给定的 ref 已初始化,则创建一个新的 MutationObserver 并将 callback 传递给它。
  4. 使用给定的 options 调用 MutationObserver.observe() 来监听给定的 ref 的变化。
  5. 当组件卸载时,使用 MutationObserver.disconnect()ref 中移除观察者。

以下是代码:

const useMutationObserver = (
  ref,
  callback,
  options = {
    attributes: true,
    characterData: true,
    childList: true,
    subtree: true
  }
) => {
  React.useEffect(() => {
    if (!ref.current) return;

    const observer = new MutationObserver(callback);
    observer.observe(ref.current, options);

    return () => observer.disconnect();
  }, [callback, options, ref]);
};

App 组件中,使用 useMutationObserver 钩子来监听对 mutationRef 元素所做的更改。incrementMutationCount 函数作为 callback 传递。

const App = () => {
  const mutationRef = React.useRef();
  const [mutationCount, setMutationCount] = React.useState(0);

  const incrementMutationCount = React.useCallback(() => {
    setMutationCount((count) => count + 1);
  }, []);

  useMutationObserver(mutationRef, incrementMutationCount);

  const [content, setContent] = React.useState("Hello world");

  return (
    <>
      <label htmlFor="content-input">编辑此内容以更新文本:</label>
      <textarea
        id="content-input"
        style={{ width: "100%" }}
        value={content}
        onChange={(e) => setContent(e.target.value)}
      />
      <div style={{ width: "100%" }} ref={mutationRef}>
        <div
          style={{
            resize: "both",
            overflow: "auto",
            maxWidth: "100%",
            border: "1px solid black"
          }}
        >
          <h2>调整大小或更改内容:</h2>
          <p>{content}</p>
        </div>
      </div>
      <div>
        <h3>变化计数 {mutationCount}</h3>
      </div>
    </>
  );
};

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

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

总结

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