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

React18中ReactDOM.render废弃后,createRoot代码未渲染页面内容求助

页面无内容显示的原因及解决方法

问题根源

你的代码中连续调用了两次root.render(),在React 18中,每次调用root.render()都会完全替换根节点内的所有内容:

  1. 第一次渲染了[title, paragraph]两个元素
  2. 紧接着第二次渲染了<StrictMode><App /></StrictMode>,如果你的App.js组件为空(比如默认React项目的初始App组件无有效内容),就会覆盖掉第一次的渲染结果,最终页面显示为空。

同时,课程提供的代码存在语法错误:ReactDOM.render()的括号未闭合,且未适配React 18的新API。


修正方案

方案1:直接渲染自定义元素(适配React 18)

移除重复的root.render()调用,将需要展示的元素放入一次渲染中:

import React from 'react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

const title = React.createElement('h1', null, 'My First React App');
const paragraph = React.createElement('p', null, 'I am creating React Nodes and using the React library');

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
  <StrictMode>
    {[title, paragraph]}
  </StrictMode>
);

方案2:沿用课程容器思路(适配React 18)

按照课程的方式创建容器元素,再通过React 18的API渲染:

import React from 'react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

const title = React.createElement('h1', null, 'My First React App');
const paragraph = React.createElement('p', null, 'I am creating React Nodes and using the React library');
const container = React.createElement('div', null, [title, paragraph]);

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
  <StrictMode>
    {container}
  </StrictMode>
);

方案3:将元素整合到App组件中

如果需要保留渲染App组件的逻辑,把自定义元素移入App.js:

// App.js
import React from 'react';

function App() {
  const title = React.createElement('h1', null, 'My First React App');
  const paragraph = React.createElement('p', null, 'I am creating React Nodes and using the React library');
  return (
    <>
      {title}
      {paragraph}
    </>
  );
}

export default App;

此时入口文件的代码可以保留:

import React from 'react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

额外检查点

  1. 确认public/index.html中存在<div id="root"></div>元素,否则createRoot无法找到挂载节点,渲染不会生效。
  2. 检查控制台是否有隐性警告(比如严格模式下的提示),确认没有其他代码逻辑影响渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 01:22:34