mirror of
https://github.com/zhigang1992/react.git
synced 2026-01-29 22:51:54 +08:00
feat(utils): add hooks for dom observer
This commit is contained in:
25
components/utils/use-dom-observer.ts
Normal file
25
components/utils/use-dom-observer.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { MutableRefObject, useEffect } from 'react'
|
||||
|
||||
const useDOMObserver = (
|
||||
ref: MutableRefObject<HTMLElement | null> | undefined,
|
||||
callback: MutationCallback = () => {},
|
||||
) => {
|
||||
const config = { attributes: false, childList: true, subtree: true }
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref || !ref.current) return
|
||||
let unmount = false
|
||||
const done: MutationCallback = (...params) => {
|
||||
if (unmount) return
|
||||
callback(...params)
|
||||
}
|
||||
const observer = new MutationObserver(done)
|
||||
observer.observe(ref.current, config)
|
||||
return () => {
|
||||
unmount = true
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [ref])
|
||||
}
|
||||
|
||||
export default useDOMObserver
|
||||
Reference in New Issue
Block a user