学完这篇,你能用 createPortal 让模态框和提示框不再被父级的 overflow:hidden、transform、z-index 截断或顶掉,并知道事件冒泡与焦点管理这两个高频问题怎么处理。
第一步:先确认这是 Portal 该解决的问题
如果弹层被裁切、被别的元素盖住、或者明明设了 z-index: 9999 还是压不住,八成是它在父节点里。以下三种父级样式是主要原因:
overflow: hidden / auto:超出部分直接裁掉;
transform、filter、will-change:父元素成为新的包含块,position: fixed 也不管用了;
- 任意
z-index + position:形成新的层叠上下文,子元素的 z-index 只在这一层内比较。
Portal 的思路很简单:React 树里还是你的子组件,但真实 DOM 挂到 document.body 下。这样渲染位置不再依赖父级样式。
第二步:准备一个挂载点
不要每次都往 body 上堆,留一个固定容器更好管理:
<!-- index.html -->
<div id="root"></div>
<div id="portal-root"></div>
#portal-root 也建议明确加上 position: relative; z-index: 1000;,跟主应用区分开层级。
第三步:写一个最小 Portal 组件
import { createPortal } from 'react-dom';
function Portal({ children, container }) {
const target = container ?? document.getElementById('portal-root');
if (!target) return null;
return createPortal(children, target);
}
createPortal(node, container, key?) 就这三个参数,第三个是给列表场景用的 key。
注意:不要写成 createPortal(children, document.createElement('div'))。每次 render 都会新建一个节点,弹层会反复重建、动画重播、输入框失焦。需要动态容器就用 useState(() => document.createElement('div')) 惰性初始化,并在 useEffect 里挂到 body、卸载时移除。
第四步:模态框完整实现
function Modal({ open, title, onClose, children }) {
useEffect(() => {
if (!open) return;
const onKey = (e) => e.key === 'Escape' && onClose();
document.addEventListener('keydown', onKey);
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden'; // 锁滚动
return () => {
document.removeEventListener('keydown', onKey);
document.body.style.overflow = prev;
};
}, [open, onClose]);
if (!open) return null;
return createPortal(
<div className="modal-mask" onClick={onClose}>
<div
className="modal-body"
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
onClick={(e) => e.stopPropagation()}
>
<h3 id="modal-title">{title}</h3>
{children}
</div>
</div>,
document.getElementById('portal-root')
);
}
要点:遮罩层负责点击关闭,内容层 stopPropagation 阻止冒泡;role="dialog" + aria-modal="true" 让读屏软件知道这是弹窗;进入时用 ref 把焦点移到弹窗内第一个可聚焦元素,关闭时还原到触发按钮。
第五步:Tooltip 的定位写法
提示框同样怕 overflow: hidden,用它最合适。定位用 fixed + getBoundingClientRect():
function Tooltip({ anchorRef, children }) {
const [pos, setPos] = useState(null);
useLayoutEffect(() => {
const update = () => {
const r = anchorRef.current?.getBoundingClientRect();
if (r) setPos({ left: r.left + r.width / 2, top: r.top - 8 });
};
update();
window.addEventListener('scroll', update, true); // true 才能捕获容器滚动
window.addEventListener('resize', update);
return () => {
window.removeEventListener('scroll', update, true);
window.removeEventListener('resize', update);
};
}, [anchorRef]);
if (!pos) return null;
return createPortal(
<div className="tooltip" style={{ left: pos.left, top: pos.top }}>
{children}
</div>,
document.body
);
}
配合 CSS transform: translate(-50%, -100%) 让气泡居中并贴在目标上方。复杂场景(自动翻转、避免溢出屏幕)建议直接上 @floating-ui/react,它本身就用 Portal。
第六步:几个必须知道的坑
注意:Portal 里的事件仍然按 React 树冒泡,不是按 DOM 树。 在 Modal 内部点按钮,外层包裹组件的 onClick 照样会触发。这就是上面 stopPropagation 的原因,别以为是 bug。
注意:CSS 继承会断。 Portal 的 DOM 不在父节点下,父级用 class 定义的字体、颜色、CSS 变量全丢了。把变量定义在 :root,或者给 portal 容器加一个同名主题 class。
注意:SSR 下 document 不存在。 首屏渲染前判断 typeof window !== 'undefined',或者组件挂在 useEffect 之后再渲染弹层,否则 Next.js 里直接报 document is not defined。
注意:多个弹层同时打开时,别硬编码 z-index。用一个自增计数器维护层级,关闭时出栈,否则后开的弹窗可能被先开的盖住。
小结
- Portal 解决的是渲染位置问题:DOM 挂到 body,React 状态和事件还在原组件树里;
- 弹窗必备四件事:Esc 关闭、遮罩点击关闭、body 滚动锁定、
role="dialog" + 焦点管理;
- Tooltip 用
fixed + getBoundingClientRect 定位,监听 scroll(记得 capture: true)和 resize 重算;
- 两个高频坑:事件按 React 树冒泡要
stopPropagation,CSS 继承会断要自己补;
- 动态创建容器节点要缓存并清理,SSR 环境先判断
window。