useMutationObserver
使用 MutationObserver MDN 检测 DOM 的更改
Usage
实时编辑器
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, }} > current width:{width} </div> <button onClick={() => setWidth(w => w + 10)}>widening</button> <button onClick={() => stop()}>stop observe</button> <p>Mutation count {count}</p> </div> ); };
结果
Loading...
API
UseMutationObserver
Returns
() => void
: 停止函数
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
callback | 回调 | MutationCallback (必填) | - |
target | dom元素 | BasicTarget (必填) | - |
options | 传递给 MutationObserver 的参数 | MutationObserverInit | undefined | - |