Skip to content

Portal

一句话解释

portal lets 你渲染组件's children 到 DOM 节点那个 exists 之外 parent's DOM hierarchy.

用大白话说

Portals provide 方式到 渲染 children 到 DOM 节点那个是 之外 current 组件's DOM 树. 你创建 one 使用 ReactDOM.createPortal(children, container), 哪里 container is a real DOM element elsewhere in the document.

The most common use case is modals, dialogs, and tooltips — these need to visually escape their parent's overflow: 隐藏 or z-索引 stacking context. With a portal, the modal renders into document.请求体 while still behaving as if it were inside the React component tree (events bubble up normally).

Even though a portal's DOM is elsewhere, its React tree position is unchanged. This means context, event bubbling, and refs all work as if the portal child were inside the parent.

示例

jsx
function Modal({ children }) {
  return ReactDOM.createPortal(
    <div className="modal">{children}</div>,
    document.body
  );
}

modal's DOM 是 appended 到 document.请求体, escaping 任何 parent overflow or z-索引 constraints, 但它 remains in React 树.

相关术语

相关资源

相关课程

  • Portals

    学习 portals for modals and overlays.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表