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
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| target | dom对象 | BasicTarget<HTMLElement | SVGElement> (必填) | - |
| initialValue | 默认值 | boolean | undefined | false |
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;