React项目报错:createRoot(...): Target container is not a DOM element 求助
解决"createRoot(...): Target container is not a DOM element"错误
错误根源在于你用了document.getElementsByClassName('root'),这个方法返回的是HTMLCollection(类数组对象),而ReactDOM.createRoot()需要传入单个DOM元素节点,不是集合。
两种修复方案:
方案1:改用ID选择器(推荐)
React项目默认的根容器在public/index.html里是用id="root"定义的,直接用getElementById获取单个元素:
import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />);
方案2:如果必须使用类选择器
从返回的集合中取出第一个元素,同时加个判断避免元素不存在的情况:
import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; const rootElement = document.getElementsByClassName('root')[0]; // 确保元素存在再渲染 if (rootElement) { const root = ReactDOM.createRoot(rootElement); root.render(<App />); }
额外检查
确认public/index.html里存在对应的根容器:
- 如果用方案1,要有:
<div id="root"></div> - 如果用方案2,要有:
<div class="root"></div>
内容的提问来源于stack exchange,提问作者Phil Dunphy
相关产品推荐
相关产品推荐

