📅  最后修改于: 2023-12-03 15:07:23.305000             🧑  作者: Mango
这是一个使用 ReactJS 构建的 JavaScript 计算器应用程序,具有漂亮的用户界面和实时计算功能。它由 HTML、CSS 和 JavaScript 组成,并使用 ReactJS 库来实现应用程序主体。
用户可以输入数字和运算符来计算其结果。应用程序还具有以下功能:
该应用程序采用了以下技术:
git clone https://github.com/username/repo.git
npm install
npm start
以下是应用程序的主要代码片段:
class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {
result: "",
history: []
};
}
handleClick = button => {
if (button === "=") {
this.calculate();
} else if (button === "C") {
this.reset();
} else if (button === "CE") {
this.backspace();
} else {
this.setState({
result: this.state.result + button
});
}
};
calculate = () => {
try {
var result = eval(this.state.result);
this.setState({
result: result,
history: [...this.state.history, this.state.result + " = " + result]
});
} catch (e) {
this.setState({
result: "error"
});
}
};
reset = () => {
this.setState({
result: "",
history: []
});
};
backspace = () => {
this.setState({
result: this.state.result.slice(0, -1)
});
};
render() {
return (
<div className="calculator">
<ResultComponent result={this.state.result} />
<KeypadComponent onClick={this.handleClick} />
<HistoryComponent history={this.state.history} />
</div>
);
}
}
class KeypadComponent extends React.Component {
handleClick = button => {
this.props.onClick(button);
};
render() {
return (
<div className="button-row">
<button className="button" onClick={() => this.handleClick("C")}>
C
</button>
<button className="button" onClick={() => this.handleClick("CE")}>
CE
</button>
<button className="button" onClick={() => this.handleClick("/")}>
÷
</button>
<button className="button" onClick={() => this.handleClick("*")}>
×
</button>
</div>
// ... Rest of code
class ResultComponent extends React.Component {
render() {
let { result } = this.props;
return (
<div className="result">
<p>{result}</p>
</div>
);
}
}
class HistoryComponent extends React.Component {
render() {
let { history } = this.props;
return (
<div className="history">
<ul>
{history.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
}
}
以下是开发这个计算器应用程序时使用的有用资源: