Skip to content

useFocus

当参考元素具有焦点时打开浮动元素,如 CSS :focus

¥Opens the floating element while the reference element has focus, like CSS :focus.

import {useFocus} from '@floating-ui/react';

要管理浮动元素本身的焦点,请使用 FloatingFocusManager

¥To manage focus within the floating element itself, use FloatingFocusManager.

用法

¥Usage

该 Hook 返回事件处理程序 props。

¥This Hook returns event handler props.

要使用它,请将 useFloating() 返回的 context 对象传递给它,然后将其结果输入 useInteractions() 数组。然后将返回的 prop getter 传播到元素上进行渲染。

¥To use it, pass it the context object returned from useFloating(), and then feed its result into the useInteractions() array. The returned prop getters are then spread onto the elements for rendering.

function App() {
  const [isOpen, setIsOpen] = useState(false);
 
  const {refs, floatingStyles, context} = useFloating({
    open: isOpen,
    onOpenChange: setIsOpen,
  });
 
  const focus = useFocus(context);
 
  const {getReferenceProps, getFloatingProps} = useInteractions([
    focus,
  ]);
 
  return (
    <>
      <div ref={refs.setReference} {...getReferenceProps()}>
        Reference element
      </div>
      {isOpen && (
        <div
          ref={refs.setFloating}
          style={floatingStyles}
          {...getFloatingProps()}
        >
          Floating element
        </div>
      )}
    </>
  );
}

属性

¥Props

interface UseFocusProps {
  enabled?: boolean;
  visibleOnly?: boolean;
}

enabled

默认:true

¥default: true

有条件地启用/禁用 Hook。

¥Conditionally enable/disable the Hook.

useFocus(context, {
  enabled: false,
});

visibleOnly

默认:true

¥default: true

打开状态是否仅在 focus 事件被视为可见时才更改(:focus-visible CSS 选择器)。

¥Whether the open state only changes if the focus event is considered visible (:focus-visible CSS selector).

useFocus(context, {
  visibleOnly: false,
});