React18中ReactDOM.render废弃后,createRoot代码未渲染页面内容求助
页面无内容显示的原因及解决方法
问题根源
你的代码中连续调用了两次root.render(),在React 18中,每次调用root.render()都会完全替换根节点内的所有内容:
- 第一次渲染了
[title, paragraph]两个元素 - 紧接着第二次渲染了
<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> );
额外检查点
- 确认
public/index.html中存在<div id="root"></div>元素,否则createRoot无法找到挂载节点,渲染不会生效。 - 检查控制台是否有隐性警告(比如严格模式下的提示),确认没有其他代码逻辑影响渲染。
内容的提问来源于stack exchange,提问作者Daniel Gedutis
相关产品推荐
相关产品推荐

