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

改写默认React JavaScript文件致白屏,如何显示Hello World?

问题解决方法

两处关键修改

1. 修正src/index.js的渲染代码(适配React 18 API)

React 18已废弃ReactDOM.render,必须使用新的createRoot API进行渲染,原代码的旧API无法在React 18环境下正常触发渲染。修改后的代码如下:

import React from 'react';
import ReactDOM from 'react-dom/client';

// 创建根节点
const root = ReactDOM.createRoot(document.getElementById('root'));
// 渲染Hello World
root.render(<h1>Hello World!</h1>);

2. 移除public/index.html中的手动引入script标签

create-react-app会自动完成JS代码的打包与注入,手动引入./src/index.js会让浏览器加载未编译的JSX文件,同时干扰正常的构建注入流程。修改后的index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <!-- 已移除手动引入的script标签 -->
  </body>
</html>

修改完成后重新执行npm start,浏览器即可正常显示Hello World!。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:52:17