我在 React 中构建了一个简单的计算器。它包含两个用于输入数字的输入,一个在单击时添加数字的按钮和一个带有结果的顶部标题,该标题具有一个onClick
动态显示结果的处理程序。
这是一个工作演示:https ://codepen.io/wawrzyniec/pen/gOmOdev
但是,当我在本地服务器上启动此项目时,代码不起作用。DOM 元素正确加载,但单击处理程序不会更改结果。我怀疑这可能与我的 Webpack 配置有关(输出不正确),但我不确定,因为我尝试了许多不同的修复程序但没有成功。
项目文件结构
.
└── 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
包.json
{
"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"
}
}
webpack.config.js
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", "*"],
},
};
.babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
./src/app.jsx
import React from "react";
import ReactDOM from "react-dom";
import Calculator from "./calculator";
document.addEventListener("DOMContentLoaded", function () {
ReactDOM.render(<Calculator />, document.getElementById("app"));
});
./src/calculator.jsx
import React from "react";
class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {
num1: "",
num2: "",
result: 0
};
this.setNum1 = this.setNum1.bind(this);
this.setNum2 = this.setNum2.bind(this);
this.add = this.add.bind(this);
}
setNum1(e) {
this.setState({ num1: Number(e.target.value) });
}
setNum2(e) {
this.setState({ num2: Number(e.target.value) });
}
add(e) {
e.preventDefault();
const sum = this.state.num1 + this.state.num2;
this.setState({ result: sum });
}
render() {
return (
<div>
<h1>{this.state.result}</h1>
<input onChange={this.setNum1} value={this.state.num1} />
<input onChange={this.setNum2} value={this.state.num2} />
<br />
<button onClick={this.add}>+</button>
</div>
);
}
}
export default Calculator;
./src/index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>React Calculator</title>
<script src="bundle.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>