mirror of
https://github.com/zhigang1992/react.git
synced 2026-04-24 04:15:54 +08:00
20 lines
517 B
TypeScript
20 lines
517 B
TypeScript
import { MutableRefObject, useEffect } from 'react'
|
|
|
|
const useClickAway = (
|
|
ref: MutableRefObject<HTMLElement | null>,
|
|
handler: (event: Event) => void,
|
|
) => {
|
|
useEffect(() => {
|
|
const callback = (event: Event) => {
|
|
const el = ref.current
|
|
if (!event || !el || el.contains((event as any).target)) return
|
|
handler(event)
|
|
}
|
|
|
|
document.addEventListener('click', callback)
|
|
return () => document.removeEventListener('click', callback)
|
|
}, [ref, handler])
|
|
}
|
|
|
|
export default useClickAway
|