React Uncaught Error:目标容器不是DOM元素

时间:2018-06-13 09:26:38

标签: javascript reactjs webpack

我最近创建了我的webpack配置文件:

const path = require("path");

const SRC_DIR = path.join(__dirname, "/client/src");
const DIST_DIR = path.join(__dirname, "/client/dist");

module.exports = {
  entry: `${SRC_DIR}/index.jsx`,
  output: {
    filename: "bundle.js",
    path: DIST_DIR
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: SRC_DIR,
        exclude: /node_modules/,
        loader: "babel-loader",
        query: {
          presets: ["react", "es2015"]
        }
      }
    ]
  },
  mode: "development"
};

这个很好用,并捆绑了jsx文件:

import React from "react";
import ReactDOM from "react-dom";

class MainApp extends React.Component {
  render() {
    return (
      <div className="content">
        <h1>Hello World</h1>
      </div>
    );
  }
}

ReactDOM.render(<MainApp />, document.getElementById("app"));

现在在html文件中我包含了带有div id app的包文件。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>REACT TEST</title>
  <script src="./bundle.js"></script>
</head>

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

</html>

当我试图运行它时,它似乎不起作用,我收到了错误:

Uncaught Error: Target container is not a DOM element.
    at invariant (invariant.js:42)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:17116)
    at Object.render (react-dom.development.js:17195)
    at eval (index.jsx:48)
    at Object../client/src/index.jsx (bundle.js:97)
    at __webpack_require__ (bundle.js:20)
    at bundle.js:84
    at bundle.js:87
invariant   @   invariant.js:42

我在这里缺少什么?为什么我收到此错误?

2 个答案:

答案 0 :(得分:6)

你拥有它的方式它甚至在你拥有DOM之前运行。

你应该把它包含在底部,如下所示:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>REACT TEST</title>
</head>

<body>
  <div id="app"></div>
  <script src="./bundle.js"></script>
</body>

</html>

答案 1 :(得分:3)

在容器初始化之前插入React脚本。像这样:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>REACT TEST</title>
</head>

<body>
  <div id="app"></div>
  <script src="./bundle.js"></script>
</body>

</html>