useMutationObserver

使用 MutationObserver MDN 检测 DOM 的更改

useMutationObserver 封装了原生 MutationObserver API,用于监视目标元素 DOM 子树中的变化。当被观察的变更发生时,它触发带有 MutationRecord 条目列表的回调。该 hook 返回一个 stop 函数,可随时断开观察器。

使用场景

  • 对第三方库控制的元素上的属性变化做出反应
  • 监控动态 DOM 变化,如内容可编辑区域中的子节点添加或删除
  • 构建实时跟踪 DOM 变更的开发工具或调试实用程序

注意事项

  • 配置:传入标准的 MutationObserverInit 选项(attributeschildListsubtreecharacterData 等)控制观察哪些类型的变更。
  • 清理:观察器在卸载时自动断开。使用返回的 stop 函数进行提前断开。
  • 参见 useResizeObserver 了解观察大小变化,以及 useIntersectionObserver 了解可见性变化。

Usage

Live Editor
function Demo() {
  const options = { attributes: true };
  const [width, setWidth] = useState(200);
  const [count, setCount] = useState(0);

  const ref = useRef<HTMLDivElement>(null);

  const stop = useMutationObserver(
    (mutationsList) => {
      mutationsList.forEach(() => setCount(c => c + 1));
    },
    ref,
    options,
  );

  useEffect(() => {
    setWidth(300);
  }, []);

  return (
    <div>
      <div
        ref={ref}
        style={{
          width,
          padding: 12,
          border: "1px solid #000",
          marginBottom: 8,
        }}
      >
        当前宽度:{width}
      </div>
      <button onClick={() => setWidth(w => w + 10)}>加宽</button>
      <button onClick={() => stop()}>停止观察</button>
      <p>变更次数 {count}</p>
    </div>
  );
};
Result

API

UseMutationObserver

Returns

() => void: 停止函数

Arguments

参数名描述类型默认值
callback回调MutationCallback (必填)-
targetdom元素BasicTarget (必填)-
options传递给 MutationObserver 的参数MutationObserverInit | undefined-

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;