目标容器不是 DOM 元素,正文中已有 div id

Target container is not a DOM element, already have div id in the body

我有一个正在运行的 npm 项目,我正在尝试将 javascript 文件 (App.js) 添加到 index.html

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

App.js

import React, { Component } from 'react';
import './App.css'

class App extends Component {

    render() {
        return "Testing"
    }
}

export default App;

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from './components/App';
import * as serviceWorker from "./serviceWorker";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import {
  Navigation,
  Footer,
  Home,
  About
} from "./components";

ReactDOM.render(<App />,
  <Router>
    <Navigation />
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
    </Routes>
    <Footer />
  </Router>,

  document.getElementById("root")
);

serviceWorker.unregister();

我收到错误消息,“目标容器不是 DOM 元素”。对此的其他答案说将 div id="root" 行放在 index.html 中,我已经完成了。如果有人可以帮我弄清楚为什么会出现此错误,那将非常有帮助。提前谢谢你。

ReactDOM.render 需要 2 个参数:要呈现的组件和父元素(即目标)。你给它 3 个参数。

您需要将您拥有的内容包装在片段中或修复 App 以实际成为包装器。

ReactDOM.render(
  <>
    <App />
    <Router>
      <Navigation />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
      <Footer />
    </Router>
  </>,
  document.getElementById("root")
);

class App extends Component {

    render() {
        return (<Router>
              <Navigation />
              <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
              </Routes>
              <Footer />
            </Router>);
    }
}
// ...
ReactDOM.render(
  <App />,
  document.getElementById("root")
);