You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React18下使用react-portal-popout@^1.9.3出现ReactDOM.render警告的解决方法

解决react-portal-popout在React 18下的ReactDOM.render警告问题

方案1:升级库到兼容React 18的版本

  • 检查react-portal-popout的最新版本,确认是否已修复React 18的API兼容问题。如果有适配版本,直接执行升级命令:
    npm update react-portal-popout
    # 或使用yarn
    yarn upgrade react-portal-popout
    
  • 若最新版本仍未兼容,可尝试锁定后续更新,或采用下面的替代方案。

方案2:自定义封装兼容React 18的弹窗组件

如果库暂未更新,可自行实现基于React 18 createRoot API的弹窗逻辑,核心步骤如下:

  1. 创建独立DOM元素作为弹窗容器,挂载到document.body
  2. 使用createRoot替代ReactDOM.render渲染弹窗内容
  3. 组件卸载时销毁root实例并清理DOM节点

示例代码:

import { createRoot } from 'react-dom/client';
import { useEffect, useRef, useState } from 'react';

const CustomPopout = ({ children, visible, onClose }) => {
  const containerRef = useRef(null);
  const rootRef = useRef(null);

  useEffect(() => {
    if (!visible) return;

    // 创建弹窗容器
    const container = document.createElement('div');
    container.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      padding: 24px;
      background: white;
      z-index: 1000;
    `;
    document.body.appendChild(container);
    containerRef.current = container;

    // 用React 18的createRoot渲染内容
    const root = createRoot(container);
    root.render(
      <div>
        {children}
        <button onClick={onClose} style={{ marginTop: '16px' }}>关闭弹窗</button>
      </div>
    );
    rootRef.current = root;

    // 清理逻辑
    return () => {
      if (rootRef.current) rootRef.current.unmount();
      if (containerRef.current) document.body.removeChild(containerRef.current);
    };
  }, [visible, children, onClose]);

  return null;
};

// 使用示例
const App = () => {
  const [showPopout, setShowPopout] = useState(false);
  return (
    <div>
      <button onClick={() => setShowPopout(true)}>打开自定义弹窗</button>
      <CustomPopout 
        visible={showPopout} 
        onClose={() => setShowPopout(false)}
      >
        <h3>这是兼容React 18的弹窗</h3>
        <p>不会触发ReactDOM.render的警告</p>
      </CustomPopout>
    </div>
  );
};

方案3:临时过滤警告(仅应急使用)

如果暂时无法升级或自定义组件,可通过过滤console.warn来隐藏该特定警告,但这只是掩盖问题,不建议长期使用:

// 在项目入口文件(如index.js)添加
const originalWarn = console.warn;
console.warn = (...args) => {
  const warningMsg = args[0];
  if (typeof warningMsg === 'string' && warningMsg.includes('ReactDOM.render is no longer supported in React 18')) {
    return;
  }
  originalWarn(...args);
};

内容的提问来源于stack exchange,提问作者Nam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:11:05