useEventListener
轻松使用 EventListener。
Usage
实时编辑器
function Demo() { const buttonRef = useRef<HTMLButtonElement>(null); const [state, setState] = useState("NO DB Click"); const onDBClick = () => { setState("DB Clicked"); }; const onClick = (event: Event) => { console.log("button clicked!", event); }; const onVisibilityChange = (event: Event) => { console.log("doc visibility changed!", { isVisible: !document.hidden, event, }); }; // example with window based event useEventListener("dblclick", onDBClick); // example with document based event useEventListener("visibilitychange", onVisibilityChange, () => document); // example with element based event useEventListener("click", onClick, buttonRef); return ( <div> <p>{state}</p> <button ref={buttonRef}>Click me</button> </div> ); };
结果
Loading...
API
useEventListener
Returns
void
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
eventName | 事件名称 | string (必填) | - |
handler | 事件处理器 | (event: any) => void (必填) | - |
element | dom元素 | EventTarget | Element | Document | HTMLElement | Window | null | undefined | window |
options | 监听选项 | boolean | AddEventListenerOptions | undefined | - |