跳到主要内容

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 (必填)-
elementdom元素EventTarget | Element | Document | HTMLElement | Window | null | undefinedwindow
options监听选项boolean | AddEventListenerOptions | undefined-