跳到主要内容

useActiveElement

React 跟踪 document.activeElement 的监听 hook

Usage

实时编辑器

function Demo() {
  const arr = [1, 2, 3, 4, 5, 6];

  const activeElement = useActiveElement<HTMLElement>();

  const key = useMemo(() => {
    return activeElement?.dataset?.id;
  }, [activeElement?.dataset?.id]);

  return (
    <div>
      <p>Select the inputs below to see the changes </p>
      <div style={{ display: "flex", gap: 15, flexWrap: "wrap" }}>
        {arr.map((i) => {
          return <input key={i} placeholder={`${i}`} data-id={i} />;
        })}
      </div>
      <br />
      <div>
        Current Active Element:
        <span> {activeElement?.tagName}</span>
      </div>
       <div>
        Current Active Element data-key:
        <span>{key}</span>
      </div>
    </div>
  );
};

render(<Demo/>)
结果
Loading...

API

useActiveElement

Returns

T | null: 返回类型参数 Tnull 的实例

Arguments