react 18 createRoot没有渲染出DOM元素

报错1

TypeError: Cannot read properties of undefined (reading
‘createElement’)

解决办法

//把import React from "react"修改为以下引用方式:
import * as React from "react";

报错2:

控制台无报错,但是createRoot没有渲染出DOM元素

createReact是把DOM元素渲染到index.html文件中的根元素下面,所以对应的解决办法如下:

  1. 检查body里面是否加上了根元素,如:
//...
<body>
	<div id="root"></div>
</body>
  1. 检查createReact引用的根元素是否正确,如:
const root = createRoot(document.getElementById("root"));
root.render(<h1>Hello world!</h1>);

此时,Hello,world就会被渲染到id="root"的元素下面;

  1. 检查react版本,react17之前的版本渲染方式和react18的不一样:
//react 17
import React from 'react';
import ReactDOM from 'react-dom';
import App from './pages/layout';

ReactDOM.render(<App />, document.getElementById('root'));

// react 18!
import * as React from "react";
import {
    
     createRoot } from "react-dom/client";

const root = createRoot(document.getElementById("root"));
root.render(<h1>Hello world!</h1>);

摘自react官网

猜你喜欢

转载自blog.csdn.net/weixin_46353030/article/details/125518123
今日推荐