使用带有 React 配置的 Webpack 的代码无法正确呈现

问题描述

我在 React 中构建了一个简单的计算器。它包含两个用于输入数字的输入,一个在点击时添加数字的按钮和一个带有结果的顶部标题,该标题具有一个 login 处理程序来动态显示结果。

这是一个工作演示:https://codepen.io/wawrzyniec/pen/gOmOdev

但是,当我在本地服务器上启动此项目时,代码不起作用。 DOM 元素正确加载,但单击处理程序不会更改结果。我怀疑这可能与我的 Webpack 配置有关(输出不正确),但我不确定,因为我尝试了许多不同的修复但都没有成功。

项目文件结构

import React from 'react'

class ChildrenComponent extends React.Component {
  render() {
    // This is doing the same thing,just we call the function / method in little different way
    // return <div onClick={() => { this.props.onShoppingSubmit() }}>Aaa</div>
    return <div onClick={this.props.onShoppingSubmit}>Aaa</div>
  }
}

class ParentComponent extends React.Component {
  handleShoppingSubmit = () => {
    // Do what every that function needs to do
    console.log('Hi from parent')
  }

  render() {
    return (
      <div>
        <ChildrenComponent onShoppingSubmit={this.handleShoppingSubmit} />
      </div>
    )
  }
}

package.json

onClick

webpack.config.js

.
└── dist
    ├── bundle.js
    ├── bundle.js.map
    └── index.html
└── node_modules
└── src
    ├── app.jsx
    ├── calculator.jsx
    └── index.html
└── .babelrc
└── package.json
└── package-lock.json
└── webpack.config.js

.babelrc

{
  "name": "react-calculator","devDependencies": {
    "@babel/core": "^7.14.0","@babel/preset-env": "^7.14.0","@babel/preset-react": "^7.13.13","babel-loader": "^8.2.2","html-webpack-plugin": "^5.3.1","webpack": "^5.36.2","webpack-cli": "^4.6.0","webpack-dev-server": "^3.11.2"
  },"scripts": {
    "start": "webpack serve","build": "webpack"
  },"dependencies": {
    "react": "^17.0.2","react-dom": "^17.0.2"
  }
}

./src/app.jsx

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/app.jsx",output: {
    filename: "bundle.js",},mode: "development",devtool: "source-map",devServer: {
    historyApiFallback: true,contentBase: path.resolve(__dirname,"./dist"),compress: true,hot: true,port: 8080,publicPath: "/dist",plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname,"./src/index.html"),}),],module: {
    rules: [
      {
        test: /\.(js|jsx)$/,exclude: /node_modules/,use: ["babel-loader"],resolve: {
    extensions: [".js",".jsx","*"],};

./src/calculator.jsx

{
  "presets": [
    "@babel/preset-env","@babel/preset-react"
  ]
}

./src/index.html

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

import Calculator from "./calculator";

document.addEventListener("DOMContentLoaded",function () {
  ReactDOM.render(<Calculator />,document.getElementById("app"));
});

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)