mirror of
https://github.com/zhigang1992/react.git
synced 2026-03-26 06:55:07 +08:00
feat: use unified away click hooks
This commit is contained in:
19
components/utils/use-click-away.ts
Normal file
19
components/utils/use-click-away.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
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
|
||||
Reference in New Issue
Block a user