📜  反应JS |计算器应用程序(样式)(1)

📅  最后修改于: 2023-12-03 15:07:23.305000             🧑  作者: Mango

反应JS | 计算器应用程序(样式)

介绍

这是一个使用 ReactJS 构建的 JavaScript 计算器应用程序,具有漂亮的用户界面和实时计算功能。它由 HTML、CSS 和 JavaScript 组成,并使用 ReactJS 库来实现应用程序主体。

功能

用户可以输入数字和运算符来计算其结果。应用程序还具有以下功能:

  • 加、减、乘、除四个基本运算符。
  • 小数点表示法。
  • 最近计算历史记录。
  • 清除当前运算和历史记录。
技术

该应用程序采用了以下技术:

  • HTML5/CSS3:用于创建漂亮的用户界面。
  • JavaScript:用于计算输入的表达式。
  • ReactJS:用于构建应用程序的组件化架构。
安装
  1. 克隆或下载仓库。
git clone https://github.com/username/repo.git
  1. 安装依赖项。
npm install
  1. 运行应用程序。
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>
    );
  }
}
参考

以下是开发这个计算器应用程序时使用的有用资源: