useFocus

跟蹤元素焦點狀態的 React Hook

useFocus 提供程式化控制 DOM 元素焦點的能力。它回傳一個布林值指示元素是否聚焦,以及聚焦和取消聚焦的控制函式。支援初始焦點設定和焦點變更事件回呼。

使用場景

  • 在模態框開啟時自動聚焦到輸入欄位
  • 程式化管理表單元素之間的焦點切換
  • 追蹤特定元素的焦點狀態以顯示視覺回饋

注意事項

  • SSR 安全:在伺服器端渲染時回傳 false 和空操作函式。伺服器上不會存取 DOM。
  • 初始焦點:設定 focusOnMount: true 可在元件掛載時自動聚焦元素。
  • 相關 hooks:另請參閱 useActiveElement 追蹤當前聚焦的元素,以及 useWindowFocus 追蹤視窗焦點。

Usage

Live Editor

function Demo() {
  const text = useRef<HTMLParagraphElement>(null);
  const input = useRef<HTMLInputElement>(null);
  const button = useRef<HTMLButtonElement>(null);

  const [paragraphFocus, setParagraphFocus] = useFocus(text);
  const [inputFocus, setInputFocus] = useFocus(input, true);
  const [buttonFocus, setButtonFocus] = useFocus(button);
  return (
    <div>
      <p ref={text} style={paragraphFocus ? { opacity: 0.5 } : {}} tabIndex={0}>
        可以被聚焦的段落
      </p>
      <input ref={input} placeholder="可以被聚焦的輸入框" />
      <br />
      <br />
      <button ref={button} style={buttonFocus ? { opacity: 0.5 } : {}}>
        可以被聚焦的按鈕
      </button>
      <br />
      <br />
      <hr />
      <p style={{ height: "2rem" }}>
        {paragraphFocus && "段落已聚焦"}
        {inputFocus && "輸入框已聚焦"}
        {buttonFocus && "按鈕已聚焦"}
      </p>
      <div>
        <button
          onClick={() => {
            setParagraphFocus(!paragraphFocus);
          }}
        >
          聚焦文本
        </button>
        <button
          onClick={() => {
            setInputFocus(!inputFocus);
          }}
        >
          聚焦輸入框
        </button>
        <button
          onClick={() => {
            setButtonFocus(!buttonFocus);
          }}
        >
          聚焦按鈕
        </button>
      </div>
    </div>
  );
};
Result

API

useFocus

Returns

readonly [boolean, (value: boolean) => void]: 包含以下元素的元組:

  • 元素是否聚焦。
  • 更新聚焦狀態。

Arguments

參數名描述類型預設值
targetdom对象BasicTarget<HTMLElement | SVGElement> (必填)-
initialValue默认值boolean | undefinedfalse

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;