跳到主要内容

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}>
        Paragraph that can be focused
      </p>
      <input ref={input} placeholder="Input that can be focused" />
      <br />
      <br />
      <button ref={button} style={buttonFocus ? { opacity: 0.5 } : {}}>
        Button that can be focused
      </button>
      <br />
      <br />
      <hr />
      <p style={{ height: "2rem" }}>
        {paragraphFocus && "The paragraph has focus"}
        {inputFocus && "The input control has focus"}
        {buttonFocus && "The button has focus"}
      </p>
      <div>
        <button
          onClick={() => {
            setParagraphFocus(!paragraphFocus);
          }}
        >
          Focus text
        </button>
        <button
          onClick={() => {
            setInputFocus(!inputFocus);
          }}
        >
          Focus input
        </button>
        <button
          onClick={() => {
            setButtonFocus(!buttonFocus);
          }}
        >
          Focus button
        </button>
      </div>
    </div>
  );
};

结果
Loading...

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;