React入门报错:ReactDOMClient is not defined 问题求助
解决ReactDOMClient未定义的问题
你遇到的ReactDOMClient is not defined错误,核心原因是ES模块的作用域隔离机制:你在type="module"标签里导入的React和ReactDOMClient只能在该模块内部访问,而你的index.js是普通全局脚本,根本拿不到这些变量。再加上当前index.js在模块脚本之前加载,就算作用域不隔离,代码执行时React相关对象还没被导入,照样报错。
另外,你的代码还有一个小问题:直接渲染<li>数组到根节点不符合React要求,React根节点只能有一个顶级元素,需要把列表项包裹在<ul>或<div>里。
推荐修复方案(遵循ES模块规范)
1. 修改index.html
把index.js改为模块脚本,调整加载顺序,并在模块中导出React对象:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple React app no JSS</title> <script type="module"> // 导入React和ReactDOMClient import React from "https://esm.sh/react@19.0.0-beta-04b058868c-20240508/?dev"; import ReactDOMClient from "https://esm.sh/react-dom@19.0.0-beta-04b058868c-20240508/client/?dev"; // 导出给index.js使用 export { React, ReactDOMClient }; </script> <!-- 将index.js改为模块脚本 --> <script type="module" src="index.js"></script> </head> <body> <div id="root"></div> </body> </html>
2. 修改index.js
导入需要的React对象,并修正渲染的根元素问题:
// 从模块中导入React和ReactDOMClient import { React, ReactDOMClient } from './index.html'; window.onload = () => { const rootElement = document.getElementById("root"); const root = ReactDOMClient.createRoot(rootElement); const ints = [1,2,3]; // 用map简化列表项创建 const childrenElements = ints.map(num => React.createElement("li", { key: num }, num) ); // 把列表项包裹在ul里 root.render(React.createElement("ul", null, childrenElements)); }
快速调试方案(不推荐用于生产环境)
如果不想调整模块结构,可以直接把React对象挂载到全局window上:
1. 修改index.html
调整脚本顺序,在模块脚本中将React挂载到全局:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple React app no JSS</title> <script type="module"> import React from "https://esm.sh/react@19.0.0-beta-04b058868c-20240508/?dev"; import ReactDOMClient from "https://esm.sh/react-dom@19.0.0-beta-04b058868c-20240508/client/?dev"; // 挂载到全局window对象 window.React = React; window.ReactDOMClient = ReactDOMClient; </script> <!-- 确保模块脚本先加载,再加载index.js --> <script src="index.js"></script> </head> <body> <div id="root"></div> </body> </html>
2. 修改index.js的渲染部分
window.onload = () => { const rootElement=document.getElementById("root"); const root = ReactDOMClient.createRoot(rootElement); const ints = [1,2,3]; const childrenElements = []; childrenElements.push( React.createElement("li", { key:ints[0] }, ints[0]) ); childrenElements.push( React.createElement("li", { key:ints[1] }, ints[1]) ); childrenElements.push( React.createElement("li", { key:ints[2] }, ints[2]) ); // 包裹在ul里 root.render(React.createElement("ul", null, childrenElements)); }
两种方案都能解决你的问题,推荐用第一种ES模块规范的方式,更符合现代前端开发的最佳实践。
内容的提问来源于stack exchange,提问作者w0051977
相关产品推荐
相关产品推荐

