Skip to content

FloatingPortal

将浮动元素传送到给定的容器元素中 - 默认情况下,在应用根目录之外并进入主体。

¥Portals the floating element into a given container element — by default, outside of the app root and into the body.

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

这是必要的,以确保浮动元素可以出现在任何导致剪切的潜在父容器(例如 overflow: hidden)之外,同时保留其在 React 树中的位置。

¥This is necessary to ensure the floating element can appear outside any potential parent containers that cause clipping (such as overflow: hidden), while retaining its location in the React tree.

function Tooltip() {
  if (isOpen) {
    return (
      <FloatingPortal>
        <div>Floating element</div>
      </FloatingPortal>
    );
  }
 
  return null;
}

提供了上下文,以便将相互嵌套的门户附加到其各自的父级。

¥Context is provided so that portals nested in one another are appended to their respective parent.

属性

¥Props

interface FloatingPortalProps {
  root?:
    | HTMLElement
    | null
    | React.MutableRefObject<HTMLElement | null>;
  id?: string;
  preserveTabOrder?: boolean;
}

root

(可选)指定门户容器将附加到的根节点。

¥Optionally specifies the root node the portal container will be appended to.

// Element
<FloatingPortal root={rootNode} />
// MutableRefObject
<FloatingPortal root={rootNodeRef} />

id

(可选)选择具有 id 的节点(如果存在),或者创建它并将其附加到指定的根(默认为 document.body)。

¥Optionally selects the node with the id if it exists, or create it and append it to the specified root (by default document.body).

<FloatingPortal id="custom-root-id" />

preserveTabOrder

默认:true

¥default: true

当使用 <FloatingFocusManager /> 使用非模态焦点管理时,这将保留基于 React 树而不是 DOM 树的 Tab 键顺序上下文。

¥When using non-modal focus management using <FloatingFocusManager />, this will preserve the tab order context based on the React tree instead of the DOM tree.

<FloatingPortal preserveTabOrder={false} />

useFloatingPortalNode()

公开门户容器节点以供在其他组件中自定义使用。

¥Exposes the portal container node for custom use in other components.

function App() {
  const portalNode = useFloatingPortalNode({
    // Accepts `id` and `root` props
  });
 
  if (portalNode) {
    return createPortal(<div />, portalNode);
  }
 
  return null;
}