Skip to content

Portals

渲染 children 之外 parent DOM hierarchy 使用 createPortal.

你将学到

  • 什么 portals 是 and 当到 use 它们
  • 创建 portal 使用 createPortal
  • 事件 bubbling 通过 portals
  • 常见 use 情况: modals, tooltips, notifications

概念讲解

What Are Portals?

Portals provide a first-class way to render children into a DOM node that exists outside the parent component's DOM hierarchy. Normally, a component renders its children inside its own DOM subtree. But sometimes you need to break out of that subtree — a modal dialog needs to overlay the entire page, a tooltip needs to escape a parent with overflow: 隐藏, or a notification needs to render at the document root. Portals let you do this while keeping the React component hierarchy intact.

Creating a Portal

You call ReactDOM.createPortal(children, 容器) where children is any renderable React content and 容器 is a DOM element. The children render inside the container, which can be anywhere in the DOM — typically a dedicated div appended to document.请求体. Despite the visual DOM separation, the React component tree remains unchanged — the portaled component is still a child in React's tree, which means context, event bubbling, and refs all work as expected.

Event Bubbling

A key feature of portals is that events bubble through the React tree, not the DOM tree. An event fired inside a portal will bubble to parent components in the React tree, even though those parents are in a different part of the DOM. This means a onClick on a parent component will still catch clicks from a portaled child. This behavior is essential for things like closing a modal when clicking outside it — the event still propagates through the React tree correctly.

Common Use Cases

The most common use cases are modals and dialogs (which need to overlay everything and escape z-index stacking contexts), tooltips and popovers (which may need to escape overflow: 隐藏 parents), notification toasts (rendered at the top level so they float above everything), and embedded widgets in third-party containers. For modals, also consider accessibility: trap focus inside the modal, handle Escape key, and restore focus when closed.

示例代码

              import { useState, useEffect } from "react";
import { createPortal } from "react-dom";

function Modal({ isOpen, onClose, children }) {
  useEffect(() => {
    const handleEsc = (e) => { if (e.key === "Escape") onClose(); };
    if (isOpen) document.addEventListener("keydown", handleEsc);
    return () => document.removeEventListener("keydown", handleEsc);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  // Render into document.body, escaping the parent's DOM hierarchy.
  return createPortal(
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-content" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}>×</button>
        {children}
      </div>
    </div>,
    document.body
  );
}

function App() {
  const [show, setShow] = useState(false);
  return (
    <div style={{ overflow: "hidden" }}>
      <p>This div has overflow hidden, but the modal escapes it.</p>
      <button onClick={() => setShow(true)}>Open Modal</button>
      <Modal isOpen={show} onClose={() => setShow(false)}>
        <h2>Modal Title</h2>
        <p>Modal content rendered via portal.</p>
      </Modal>
    </div>
  );
}
            

createPortal 渲染 modal 到 document.请求体, escaping parent's overflow:隐藏. 事件 still bubble 通过 React 树. Escape 键关闭 modal.

动手试一试

  • Code Diff

    Compare modal implementations 使用 and 不使用 portals.

  • CSS Gradient Generator

    设计 overlay and backdrop 样式 for 你的 portal-based modals.

常见错误

错误写法

创建新 portal 容器 on 每个渲染

正确做法

创建 portal 容器一次 (in useEffect on mount or as 模块-level 元素) and clean 它上 on unmount. 创建它 on 每个渲染 causes memory leaks and flickering.

错误写法

Forgetting 到 handle accessibility for modals

正确做法

Modals 需要 focus trapping, Escape 键 handling, aria-modal attribute, and focus restoration on 关闭. Use 库如 react-focus-lock or implement 这些 manually for accessibility compliance.

练习 Portals

3 个练习

练习 Portals

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

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

查看错误