feat: use unified away click hooks

This commit is contained in:
unix
2020-03-25 02:01:13 +08:00
parent f824375374
commit ba0975e71d
3 changed files with 28 additions and 14 deletions

View 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