( fn: (e: KeyboardEvent) => void, options?: AddEventListenerOptions )
| 6 | * 仅接受最初的函数 |
| 7 | */ |
| 8 | export function useGlobalKeyDown( |
| 9 | fn: (e: KeyboardEvent) => void, |
| 10 | options?: AddEventListenerOptions |
| 11 | ) { |
| 12 | const fnRef = useUpdateRef(fn); |
| 13 | |
| 14 | useLayoutEffect(() => { |
| 15 | const handleKeyDown = (e: KeyboardEvent) => { |
| 16 | typeof fnRef.current === 'function' && fnRef.current(e); |
| 17 | }; |
| 18 | |
| 19 | window.addEventListener('keydown', handleKeyDown, options); |
| 20 | |
| 21 | return () => { |
| 22 | window.removeEventListener('keydown', handleKeyDown, options); |
| 23 | }; |
| 24 | }, []); |
| 25 | } |
no test coverage detected