reactjs 从react-dom/client导入createRoot时出现问题

knpiaxh1  于 2023-03-22  发布在  React
关注(0)|答案(6)|浏览(553)

在使用create-react-app并将index.js ReactDOM.render更新到React 18之后,我得到了这个错误:“警告:您正在从不受支持的'react-dom'导入createRoot。您应该从'react-dom/client'导入它”。
Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { createRoot } from 'react-dom/client';
import Switch from './components/Switch';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Switch />
  </React.StrictMode>
);
xienkqul

xienkqul1#

收到的错误消息指示您应该从react-dom/client而不是react-dom导入createRoot方法。
要解决这个问题,只需修改createRoot的import语句,如下所示:

import { createRoot } from 'react-dom/client';

所以修改后的代码应该是这样的:

import React from 'react';
import ReactDOM from 'react-dom';
import { createRoot } from 'react-dom/client';
import Switch from './components/Switch';

const root = createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Switch />
  </React.StrictMode>
);
jckbn6z7

jckbn6z72#

对于所有类型脚本用户,如果您收到经典的 *“未找到此模块的类型”警告,请添加此警告。

src/react-app-env.d.ts

declare module "react-dom/client" {
  // typing module default export as `any` will allow you to access its members without compiler warning
  var createRoot: any;
  export {createRoot};
}
jyztefdp

jyztefdp3#

确保你的react-dom版本是"^18.0.0"

rdlzhqv9

rdlzhqv94#

你可以这样做:

import React from 'react';
import { createRoot } from 'react-dom/client';
import Switch from './components/Switch';

const root = createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Switch />
  </React.StrictMode>
);

我使用了从react-dom/client导入的createRoot,并删除了未使用的ReactDOM的导入

w1jd8yoj

w1jd8yoj5#

Necesitas agregar '/client' cuando importas 'ReactDOM'
导入'ReactDOM'时需要添加'/client'。

import React from 'react';
import ReactDOM from 'react-dom/client';
import Switch from './components/Switch';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Switch />
  </React.StrictMode>
);
wvmv3b1j

wvmv3b1j6#

现在在React 18+中,你可以这样做:

import React from 'react'
import ReactDOM from 'react-dom/client'
import Switch from './components/Switch'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
    <React.StrictMode>
        <Switch />
    </React.StrictMode>,
)

相关问题