【问题标题】:Need to add a simple functionality to a simple calculator made in React JS需要为 React JS 制作的简单计算器添加一个简单的功能
【发布时间】:2020-03-17 17:21:29
【问题描述】:

我用 React JS 做了简单的计算器。所有功能都运行良好,但我需要实现这两个我遇到麻烦的功能:

1) 当点击操作符(+或-)时,如果再次点击操作符,则操作符应该被替换。例如,如果用户单击 +,则在该用户单击 - 之后,然后进行减法运算 将执行而不是添加

2) 应执行操作顺序。例如,如果用户输入 5 然后 + 和 然后是 4,然后是 -,它应该计算 5+4 并在文本框/标签中显示 9

如果链接在这里不起作用是我的代码

import React from "react"
import "./style.css"
import "./App.css"


class Layout extends React.Component{
    constructor(){
        super()
        this.state ={
            text: "",
            result: [],
            prevResult: []
        }
        this.handleChange = this.handleChange.bind(this)
        this.calculate = this.calculate.bind(this)
        this.back = this.back.bind(this)
    }

    handleChange(event){ 
        const {name, value, type, checked} = event.target
        this.setState({[name]: value})
    }

    calculate(event){
        this.setState((prevState) => ({
            text: (eval(this.state.text) || "" ) + "",
            result: [...prevState.result, this.state.text + "   " ],
            prevResult: [...prevState.prevResult,  + (eval(this.state.text) || "" ) + "  " ]
            })
        ) 
    }
    back(event){
        const {name, value, type, checked} = event.target
        type === "abc" ? this.setState({text: this.state.text.slice(0, -1)}) : this.setState({text: ""})
    }

    render(){
        return(
           <div > 
            <div className= "resultbar">
               <input style= {{height: "30px", width: "200px", font: "20px" }}
                    name="text"
                    autoFocus="autofocus" 
                    value={this.state.text}
                    onChange = {this.handleChange} 
               />
            </div>

            <div className= "history">
                <h2>History</h2>
                <h3 style= {{color: "red" }}>{this.state.result} </h3>
                <p>{this.state.prevResult}</p>

            </div>

            <div className="button">
                <button 
                    name= "text"
                    value = {this.state.text + "+"}
                    onClick= {this.handleChange}>+</button>

                <button
                    name= "text"
                    value = {this.state.text + "-"}
                    onClick= {this.handleChange}>-</button>

                <button
                    type= "adbc"
                    name= "text"
                    value = {this.state.text + "*"}
                    onClick= {this.handleChange}>*</button>

                <button
                    name= "text"
                    value = {this.state.text + "/"}
                    onClick= {this.handleChange}>/</button>

                <button
                    name= "text"
                    value = {this.state.text + "%"}
                    onClick= {this.handleChange}>%</button>

                <button
                    name= "text"
                    value = {this.state.text + "("}
                    onClick= {this.handleChange}>(</button>

                <button
                    name= "text"
                    value = {this.state.text + ")"}
                    onClick= {this.handleChange}>)</button>

                <button
                    name= "text"
                    type= "dbac"
                    value= {this.state.text}
                    onClick = {this.calculate}>=</button>

                <button 
                    name= "text"
                    value = {this.state.text + "1"}
                    onClick= {this.handleChange}>1</button>

                <button
                    name= "text"
                    value = {this.state.text + "2"}
                    onClick= {this.handleChange}>2</button>

                <button
                    name= "text"
                    value = {this.state.text + "3"}
                    onClick= {this.handleChange}>3</button>

                <button 
                    name= "backspace"
                    onClick = {() => this.setState({
                    text: this.state.text.slice(0, -1)
                    })}> Ce</button>

                <button
                    name= "text"
                    value = {this.state.text + "4"}
                    onClick= {this.handleChange}>4</button>

                <button
                    name= "text"
                    value = {this.state.text + "5"}
                    onClick= {this.handleChange}>5</button>

                <button
                    name= "text"
                    value = {this.state.text + "6"}
                    onClick= {this.handleChange}>6</button>

                <button
                    name= "text"
                    type= "abc"
                    onClick = {this.back} 
                    >C</button>

                <button
                    name= "text"
                    value = {this.state.text + "7"}
                    onClick= {this.handleChange}>7</button>
                <button
                    name= "text"
                    value = {this.state.text + "8"}
                    onClick= {this.handleChange}>8</button>

                <button
                    name= "text"
                    value = {this.state.text + "9"}
                    onClick= {this.handleChange}>9</button>

                <button 
                    name= "backspace"
                    onClick = {() => this.setState({
                    text: this.state.text.slice(0, -1)
                    })}> ~</button>

                <button
                    name= "text"
                    value = {this.state.text + "."}
                    onClick= {this.handleChange}>.</button>

                <button
                    name= "text"
                    value = {this.state.text + "0"}
                    onClick= {this.handleChange}>0</button>
            </div>
        </div>
        )
    }
}
export default Layout

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您需要检查过去的字符串值,如果最后一个字符是运算符而不是更新运算符。电池使用计算器算法基于堆栈。只需将元素压入栈中 if number,替换 if 运算符,计算 if =。

    1. 不要修改按钮的值 (value={this.state.text + ")"})
    2. 在函数中写逻辑

    // 清理代码。 https://codesandbox.io/s/eager-haze-gi30v

    import React from "react";
    import "./style.css";
    import "./App.css";
    const operators = ["+", "-", "/", "*", "%"];
    
    class Layout extends React.Component {
      constructor() {
        super();
        this.state = {
          text: "",
          result: [],
          prevResult: []
        };
        this.handleChange = this.handleChange.bind(this);
        this.calculate = this.calculate.bind(this);
        this.onChange = this.onChange.bind(this);
      }
    
      handleChange(event) {
        const { name, value } = event.target;
    
        let text = this.state.text;
        let lastChar = text.charAt(text.length - 1);
        const isOperator = operators.indexOf(value) !== -1;
        if (value === "=") {
          this.setState(prevState => this.calculate(prevState));
        } else if (value === "CE") {
          this.setState({ text: text.slice(0, -1) });
        } else if (value === "C") {
          this.setState({ text: "" });
        } else if (isOperator && operators.indexOf(lastChar) !== -1) {
          text = text.substr(0, text.length - 1) + value;
          this.setState({ [name]: text });
        } else {
          this.setState({ [name]: text + value });
        }
      }
      onChange({ target }) {
        this.setState({ text: target.value });
      }
      calculate(prevState) {
        try {
          const text = (eval(this.state.text) || "") + "";
          return {
            text,
            result: [...prevState.result, this.state.text + "   "],
            prevResult: [...prevState.prevResult, +text]
          };
        } catch (event) {
          return {
            text: "error",
            result: "error",
            prevResult: "error"
          };
        }
      }
      render() {
        const buttons = [
          "+",
          "-",
          "*",
          "/",
          "%",
          "(",
          ")",
          "=",
          "1",
          "2",
          "3",
          "CE",
          "4",
          "5",
          "6",
          "C",
          "7",
          "8",
          "9",
          "~",
          ".",
          "0"
        ];
        return (
          <div>
            <div className="resultbar">
              <input
                style={{ height: "30px", width: "200px", font: "20px" }}
                name="text"
                autoFocus="autofocus"
                value={this.state.text}
                onChange={this.onChange}
              />
            </div>
    
            <div className="history">
              <h2>History</h2>
              <h3 style={{ color: "red" }}>{this.state.result} </h3>
              <p>{this.state.prevResult}</p>
            </div>
            <div className="button">
              {buttons.map(x => {
                return (
                  <button name="text" value={x} onClick={this.handleChange}>
                    {x}
                  </button>
                );
              })}
            </div>
          </div>
        );
      }
    }
    export default Layout;
    

    【讨论】:

    • 更新你的样本
    • @moeez-atlas 我现在有清理代码更多检查。 #moeez-atlas
    • 是的,它现在看起来干净多了。谢谢
    • 你能帮我解决第二个功能吗?遇到麻烦了。
    • 完成请检查!叹!! codesandbox.io/embed/…
    猜你喜欢
    • 2016-11-19
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2014-05-20
    相关资源
    最近更新 更多