react 18 createRoot does not render DOM elements

error 1

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

Solution

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

Error 2:

There is no error in the console, but createRoot does not render the DOM element

createReact renders the DOM element below the root element in the index.html file, so the corresponding solution is as follows:

  1. Check whether the root element is added to the body, such as:
//...
<body>
	<div id="root"></div>
</body>
  1. Check whether the root element referenced by createReact is correct, such as:
const root = createRoot(document.getElementById("root"));
root.render(<h1>Hello world!</h1>);

At this point, Hello, world will be rendered under the element with id="root";

  1. Check the react version, the rendering method of the version before react17 is different from that of 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>);

Excerpted from react official website

おすすめ

転載: blog.csdn.net/weixin_46353030/article/details/125518123