1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | import {RefObject} from '@react-types/shared';
|
14 | import {useEffect} from 'react';
|
15 | import {useEffectEvent} from './useEffectEvent';
|
16 |
|
17 | export function useEvent<K extends keyof GlobalEventHandlersEventMap>(
|
18 | ref: RefObject<EventTarget | null>,
|
19 | event: K | (string & {}),
|
20 | handler?: (this: Document, ev: GlobalEventHandlersEventMap[K]) => any,
|
21 | options?: boolean | AddEventListenerOptions
|
22 | ) {
|
23 | let handleEvent = useEffectEvent(handler);
|
24 | let isDisabled = handler == null;
|
25 |
|
26 | useEffect(() => {
|
27 | if (isDisabled || !ref.current) {
|
28 | return;
|
29 | }
|
30 |
|
31 | let element = ref.current;
|
32 | element.addEventListener(event, handleEvent as EventListener, options);
|
33 | return () => {
|
34 | element.removeEventListener(event, handleEvent as EventListener, options);
|
35 | };
|
36 | }, [ref, event, options, isDisabled, handleEvent]);
|
37 | }
|