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;
stickIfOpen?: 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).
useClick(context, {
ignoreMouse: true,
});
keyboardHandlers
默认:true
¥default: true
是否为非按钮元素添加键盘处理程序(Enter
和 Space
键功能)(通过键盘 “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,
});
stickIfOpen
默认:true
¥default: true
如果已经从另一个事件(例如 useHover()
Hook)打开,则确定在第一次单击参考元素时是否保持浮动元素打开。
¥If already open from another event such as the useHover()
Hook, determines whether to keep the floating element open when
clicking the reference element for the first time.
useClick(context, {
stickIfOpen: false,
});