渲染组件直接警告

Rendering components directly warning

一段时间以来我一直收到以下警告,我不确定问题到底是什么:

Warning: render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try rendering into a container element created for your app.

有些人建议使用 ReactDOM.render() 这正是我最初所做的,我使用 facebook 的 Create React App 作为我的应用程序的基础。

有什么线索吗?


编辑:我的 index.js

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

如果您的 index.html 中的 html 正文标签具有 root id,就会出现此问题。

在您的 index.html 更改中:

<body id="root"></body>

至:

<body>
   <div id="root"></div>
</body>

这里有 2 种可能的解决方案:

  1. 修改您的 HTML 并添加 <div> 并将其用于渲染 (推荐):

ReactDOM.render(<App />, document.getElementById('react-app'));
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React app</title>
</head>
<body>
    <div id="react-app"></div>
</body>
</html>

  1. 使用 JavaScript 创建一个元素并将其附加到正文并使用它来呈现:

var reactapp = document.createElement("div");
document.body.appendChild(reactapp);
ReactDOM.render(<App />, reactapp);