React中createPortal 的详细用法

createPortal 是 React 提供的一个实用工具,用于将 React 子元素渲染到 DOM 中的某个位置,而该位置与父组件不在同一个 DOM 层次结构中。这在某些特殊场景下非常有用,比如实现模态框、弹出菜单、固定定位元素等功能。

基本语法

JavaScript

复制

复制代码
const portal = createPortal(child, container);
  • child 是要渲染的 React 子元素。

  • container 是 DOM 元素,子元素将被渲染到这个元素中。

使用场景

  1. 模态框:将模态框的内容渲染到 body 的顶层,以确保模态框不会被其他元素遮挡。

  2. 弹出菜单:将弹出菜单渲染到 body 的顶层,以确保菜单不会被其他元素遮挡。

  3. 固定定位元素:将固定定位的元素渲染到 body 的顶层,以确保元素的定位不会受到父元素的影响。

示例

下面是一个使用 createPortal 实现模态框的示例:

复制代码
import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';

function Modal() {
  const [showModal, setShowModal] = useState(false);

  // 创建一个 DOM 元素作为模态框的容器
  const modalRef = React.useRef(document.createElement('div'));

  useEffect(() => {
    // 将模态框容器添加到 body 中
    document.body.appendChild(modalRef.current);
    return () => {
      // 组件卸载时移除模态框容器
      document.body.removeChild(modalRef.current);
    };
  }, []);

  return (
    <>
      <button onClick={() => setShowModal(true)}>Open Modal</button>

      {showModal && (
        createPortal(
          <div className='modal-overlay'>
            <div className='modal'>
              <h2>Modal Title</h2>
              <p>This is a modal content</p>
              <button onClick={() => setShowModal(false)}>Close Modal</button>
            </div>
          </div>,
          modalRef.current
        )
      )}
    </>
  );
}

export default Modal;
CSS
复制代码
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  width: 300px;
}

优点

  • 灵活性:可以将子元素渲染到 DOM 中的任意位置。

  • 避免样式冲突:通过将元素渲染到不同的 DOM 层次结构中,可以避免样式冲突。

  • 优化性能:通过减少不必要的 DOM 操作,可以优化性能。

注意事项

  • 清理资源:在组件卸载时,确保移除创建的 DOM 元素,以避免内存泄漏。

  • 样式隔离:确保渲染到不同 DOM 层次结构中的元素不会受到其他样式的影响。

总结

createPortal 是 React 提供的一个强大工具,用于将子元素渲染到 DOM 中的任意位置。通过使用 createPortal,可以实现模态框、弹出菜单等功能,并确保这些元素的样式和行为不受父组件的影响。

以下是一个更完整的示例,展示如何使用 createPortal 实现一个模态框:

复制代码
import React, { useState } from 'react';
import { createPortal } from 'react-dom';

function Modal() {
  const [showModal, setShowModal] = useState(false);

  // 创建一个 DOM 元素作为模态框的容器
  const modalRef = React.useRef(document.createElement('div'));

  // 将模态框容器添加到 body 中
  useEffect(() => {
    document.body.appendChild(modalRef.current);
    return () => {
      document.body.removeChild(modalRef.current);
    };
  }, []);

  return (
    <>
      <button onClick={() => setShowModal(true)}>Open Modal</button>

      {showModal && (
        createPortal(
          <div className='modal-overlay'>
            <div className='modal'>
              <h2>Modal Title</h2>
              <p>This is a modal content</p>
              <button onClick={() => setShowModal(false)}>Close Modal</button>
            </div>
          </div>,
          modalRef.current
        )
      )}
    </>
  );
}

export default Modal;

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  width: 300px;
  max-height: 80vh;
  overflow-y: auto;
}

在这个示例中,模态框的内容被渲染到一个独立的 DOM 容器中,该容器被添加到 body 中。这确保了模态框不会被其他元素遮挡,并且可以独立于父组件进行样式控制。

相关推荐
恋猫de小郭10 分钟前
为什么跨平台框架可以适配鸿蒙,它们的技术原理是什么?
android·前端·flutter
云浪13 分钟前
元素变形记:CSS 缩放函数全指南
前端·css
明似水28 分钟前
用 Melos 解决 Flutter Monorepo 的依赖冲突:一个真实案例
前端·javascript·flutter
独立开阀者_FwtCoder38 分钟前
stagewise:让AI与代码编辑器无缝连接
前端·javascript·github
清沫40 分钟前
Cursor Rules 开发实践指南
前端·ai编程·cursor
江城开朗的豌豆1 小时前
JavaScript篇:对象派 vs 过程派:编程江湖的两种武功心法
前端·javascript·面试
不吃糖葫芦31 小时前
App使用webview套壳引入h5(二)—— app内访问h5,顶部被手机顶部菜单遮挡问题,保留顶部安全距离
前端·webview
菥菥爱嘻嘻1 小时前
JS手写代码篇---手写ajax
开发语言·javascript·ajax
江城开朗的豌豆1 小时前
JavaScript篇:字母侦探:如何快速统计字符串里谁才是'主角'?
前端·javascript·面试
kite01217 小时前
浏览器工作原理06 [#]渲染流程(下):HTML、CSS和JavaScript是如何变成页面的
javascript·css·html