在练习官网案例时,使用create-react-app创建项目后,删除src下所有文件,新建了index.html、index.css、index.js。其中:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
index.js:
const root = ReactDOM.createRoot(document.getElementById("container"));
//const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<FilterableProductTable products={PRODUCTS} />);
当使用getElementById("hello")时报错:react-dom.development.js:29345 Uncaught Error: createRoot(...): Target container is not a DOM element.
当使用getElementById("root")时正常。
网上该报错原因多是getElementById中参数填写错误,与html中的id不一致。不过本次id均一致填写了"container"。
后在新项目中发现默认index.html文件应在public目录下,而非src目录下,默认index.html中有root节点,所以当使用getElementById("root")时正常。
解决方法:将自己编写的index.html放到public目录下。