跳至主要内容

useFocus

跟蹤元素焦點狀態的 React Hook

Usage

即時編輯器

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>
  );
};

結果

可以被聚焦的段落






輸入框已聚焦

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;
ads via Carbon