Skip to content

useClick

单击参考元素时打开或关闭浮动元素。

¥Opens or closes the floating element when clicking the reference element.

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

用法

¥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 click = useClick(context);
 
  const {getReferenceProps, getFloatingProps} = useInteractions([
    click,
  ]);
 
  return (
    <>
      <div ref={refs.setReference} {...getReferenceProps()}>
        Reference element
      </div>
      {isOpen && (
        <div
          ref={refs.setFloating}
          style={floatingStyles}
          {...getFloatingProps()}
        >
          Floating element
        </div>
      )}
    </>
  );
}

属性

¥Props

interface UseClickProps {
  enabled?: boolean;
  event?: 'click' | 'mousedown';
  toggle?: boolean;
  ignoreMouse?: boolean;
  keyboardHandlers?: boolean;
}

enabled

默认:true

¥default: true

有条件地启用/禁用 Hook。

¥Conditionally enable/disable the Hook.

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

event

默认:'click'

¥default: 'click'

用于确定带有鼠标输入的 “click” 的事件类型。键盘点击操作正常。

¥The type of event to use to determine a “click” with mouse input. Keyboard clicks work as normal.

useClick(context, {
  event: 'mousedown',
});

toggle

默认:true

¥default: true

是否通过重复点击切换打开状态。

¥Whether to toggle the open state with repeated clicks.

useClick(context, {
  toggle: false,
});

ignoreMouse

默认:false

¥default: false

是否忽略鼠标输入的逻辑(例如,如果 useHover() 也正在使用)。

¥Whether to ignore the logic for mouse input (for example, if useHover() is also being used).

useHover()useClick() 一起使用时,悬停后单击参考元素,即使光标离开,浮动元素也会保持打开状态。在某些情况下这可能是不可取的。

¥When useHover() and useClick() are used together, clicking the reference element after hovering it will keep the floating element open even once the cursor leaves. This may be not be desirable in some cases.

useClick(context, {
  ignoreMouse: true,
});

keyboardHandlers

默认:true

¥default: true

是否为非按钮元素添加键盘处理程序(EnterSpace 键功能)(通过键盘 “click” 打开/关闭浮动元素)。

¥Whether to add keyboard handlers (Enter and Space key functionality) for non-button elements (to open/close the floating element via keyboard “click”).

useClick(context, {
  keyboardHandlers: false,
});