Skip to content

useClientPoint

将浮动元素定位在给定的客户端点 (x, y),通常由鼠标事件生成。默认情况下,会自动跟踪客户端的鼠标位置。

¥Positions the floating element at a given client point (x, y), usually generated by a mouse event. By default, the client’s mouse position is automatically tracked.

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

这对于将浮动元素定位在给定点非常有用,同时还允许锚定在滚动时跟随该点。

¥This is useful to position a floating element at a given point, while also allowing anchoring to follow the point upon scroll.

用法

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

默认行为是跟随鼠标光标 clientXclientY 坐标。

¥The default behavior is to follow the mouse cursor clientX and clientY coordinates.

指针事件

¥Pointer events

如果浮动元素不可交互,请禁用指针事件:

¥If the floating element is not interactive, disable pointer events:

.floating {
  pointer-events: none;
}

这将确保浮动元素不会阻止点更新。

¥This will ensure that the floating element does not block point updates.

属性

¥Props

interface UseClientPointProps {
  enabled?: boolean;
  axis?: 'both' | 'x' | 'y';
  x?: number | null;
  y?: number | null;
}

enabled

默认:true

¥default: true

有条件地启用/禁用 Hook。

¥Conditionally enable/disable the Hook.

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

axis

默认:'both'

¥default: 'both'

是否将客户端点限制为一个轴并使用参考元素(如果存在)作为另一个轴。如果浮动元素也是交互式的,这会很有用。

¥Whether to restrict the client point to an axis and use the reference element (if it exists) as the other axis. This can be useful if the floating element is also interactive.

useClientPoint(context, {
  axis: 'x',
});

x

默认:null

¥default: null

明确定义的 x 客户端坐标。

¥An explicitly defined x client coordinate.

useClientPoint(context, {
  x: 100,
});

y

默认:null

¥default: null

明确定义的 y 客户端坐标。

¥An explicitly defined y client coordinate.

useClientPoint(context, {
  y: 100,
});