React Component未加载Webpack和Babel Beginner的级别

时间:2019-03-22 09:38:47

标签: javascript reactjs webpack babeljs babel-loader

我试图了解React,Babel和Webpack如何相互交互,但是出现以下错误:Uncaught TypeError:超级表达式必须为null或函数。 CSS可以很好地呈现,但是HTML却不能,尽管我能够在控制台中看到它(见下图)。 有什么建议么?

package.json

{
  "name": "react-raw",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ]
  },
  "scripts": {
    "start": "webpack-dev-server --open"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.8.4",
    "react-dom": "^16.8.4"
  },
  "devDependencies": {
    "@babel/core": "^7.4.0",
    "@babel/preset-env": "^7.4.1",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.5",
    "css-loader": "^2.1.1",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.2.1"
  }
}

index.js

var React = require("react");
var ReactDOM = require("react-dom");

require("./index.css");

class App extends React.Component() {
  render() {
    return <div>Hello Christian!!</div>;
  }
}

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

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin"); //installed via npm
//const webpack = require("webpack"); //to access built-in plugins

module.exports = {
  entry: "./app/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "index_bundle.js"
  },
  module: {
    rules: [
      { test: /\.(js)$/, use: "babel-loader" },
      { test: /\.css$/, use: ["style-loader", "css-loader"] }
    ]
  },
  mode: "development",
  plugins: [new HtmlWebpackPlugin({ template: "app/index.html" })]
};

index.html

<!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 Raw</title>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

TypeError

Element is rendered

enter image description here

1 个答案:

答案 0 :(得分:1)

您的问题出在您的class组件的签名上:

class App extends React.Component() {
  render() {
    return <div>Hello Christian!!</div>;
  }
}

这是您需要声明的方式:

class App extends React.Component{
  render() {
    return <div>Hello Christian!!</div>;
  }
}

请注意,我省略了多余的()

您可以在here

中了解有关类的更多信息