簡體   English   中英

bundle.js中未捕獲的錯誤用於reactjs

[英]Uncaught error in bundle.js for reactjs

我開始使用React js,構建我的第一個組件,但我陷入了這個錯誤

"Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined."

我正在使用的編輯器是Visual Studio 2017。

webpack.config.js的代碼是

module.exports = {
  context: __dirname,
  entry: "./app.js",
  output: {
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  watch: true,
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      use:
        {
          loader: 'babel-loader',
          options: {
            presets: ['babel-preset-env', 'babel-preset-react', ]
          }
        }
    }
    ]
  }
}

app.js

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

ReactDOM.render(
    <Button />,
    document.getElementById('root')
);

class Button extends React.Component {
    render() {
        return (<button>42</button>);
    }
}

我正在渲染的頁面是index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index test</h2>

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

@section scripts{

    <script src="~/Scripts/React/dist/bundle.js"></script>
}

我在app.js中進行更改后,下一步是轉到cmd提示符並執行npm運行webpack。

謝謝您的幫助

在聲明組件之前,您正在使用該組件。 這不起作用,因為javascript類不會被吊起。 這應該工作

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

class Button extends React.Component {
    render() {
        return (<button>42</button>);
    }
}

ReactDOM.render(
    <Button />,
    document.getElementById('root')
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM