React Calculator-如何将大于9的数字相加?

javascripting

我有一个具有基本功能(+-/ 的React计算器,我要这样做的方法是看到结果,而不是按=后,而是按任何运算符(+-/)时。我的问题是我想不出一种好方法来处理大于9的数字,而无论我尝试什么,我都会弄乱结果或显示出什么。任何帮助都将非常棒。谢谢!!

我也将其放在Codepen上,以便更好地查看:https ://codepen.io/julianyc/pen/bXwxbg?editors=1010

  const math_it_up = {
      '+': function (x, y) {
          return x + y
      },
      '-': function (x, y) {
          return x - y
      },
      '*': function (x, y) {
          return x * y
      },
      '/': function (x, y) {
          return x / y
      }
  }

  class App extends React.Component {
    state = {
          result: 0,
          operator: "",
          currentNum: "",
          show: 0
      };

      onClick = (elem) => {

          if (isNaN(elem)) {
              if (elem === "=") {
                  this.setState({
                      show: this.state.result
                  })
              } else {
                  this.setState({
                      operator: elem,
                      show: this.state.result ? this.state.result : null
                  })
              }

          }

          else {
              if (!this.state.currentNum) {
                  this.setState({
                      currentNum: parseInt(elem),
                      result: parseInt(elem),
                      show: elem
                  })
              } else {
                  if (this.state.operator) {
                      this.setState({
                          currentNum: parseInt(elem),
                          result: math_it_up[this.state.operator](this.state.result, parseInt(elem)),
                          show: elem
                      })
                  }

              }

          }

      };

      render() {      
          return (
              <div>
                  <Key onClick={this.onClick}/>
                  <h1>{this.state.show}</h1>
              </div>
          )
      }
  }

  const Key = ({onClick}) => {

      const renderNumbers = () => {
         const arr = [0,1,2,3,4,5,6,7,8,9];
          return arr.map((val, i) => {
              return <button key={i} name={val} onClick={(e) => onClick(e.target.name)}>{val}</button>
          })
      };

      const renderCalculationKeys = () => {
          const arr = ["+", "-", "/", "*", "="];
          return arr.map((val, i) => {
              return <button key={i} name={val} onClick={(e) => onClick(e.target.name)}>{val}</button>
          })
      };

      return (
          <div>
              {renderNumbers()}
              {renderCalculationKeys()}
          </div>
      )
  };
斯巴达克斯

尝试使用与此类似的逻辑。当然,您可以通过数千种不同的方式来实现此目的,这只是其中之一。

我认为代码是不言自明的。基本上,您将输入的数字添加到状态中保存的数字的末尾,如果字符串为0,则用输入的数字覆盖它。

const Calculate = {
  '+': (x, y) => x + y,
  '-': (x, y) => x - y,
  '*': (x, y) => x * y,
  '/': (x, y) => x / y
}

const Keys = ({ onClick, operator }) => {
  return (
    <div className="buttons">
      {[1,2,3,'+',4,5,6,'-',7,8,9,'/','C',0,'=','*'].map(val => {
        return (
          <button
            key={val.toString()}
            name={val}
            onClick={(e) => onClick(e.target.name)}
            className={operator && operator === val ? 'is-active' : ''}
          >
            {val}
          </button>
        )
      })}
    </div>
  )
}

const App = () => {
  const [x, setX] = React.useState(0);
  const [y, setY] = React.useState(null);
  const [operator, setOperator] = React.useState(null);

  const onClick = n => {
    const operators = ['-','+','*','/']
    if (isNaN(n)) {
      if (operators.includes(n)) {
        if (y !== null) {
          setX(Calculate[operator](x, y))
          setY(null)
        }
        setOperator(n)
      }
      if (n === 'C') {
        setX(0)
        setY(null)
        setOperator(null)
      }
      if (n === '=' && y !== null) {
        setX(Calculate[operator](x, y))
        setY(null)
        setOperator(null)
      }
    } else {
      const setNumber = (v, n) => {
        if (v === 0 || v === null) v = ''
        return parseInt(v.toString() + n)
      }
      if (operator !== null || y !== null) setY(setNumber(y, n))
      else setX(setNumber(x, n))
    }
  }
    
  return (
    <div className="calculator">
      <h1 className="display">{y !== null ? y : x}</h1>
      <Keys onClick={onClick} operator={operator && y === null ? operator : null}/>
    </div>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
 );
@import url('https://fonts.googleapis.com/css?family=Roboto+Mono:300&display=swap');

html {
  font-size: 6px;
}

body {
  background: #111;
  font-family: 'Roboto Mono';
  font-weight: 300;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
}

#root {
  position: absolute;
  min-height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

* {
  margin: 0;
  padding: 0;
  font: inherit;
  box-sizing: border-box;
}

body button {
  -moz-appearance: none;
  -webkit-appearance: none;
  background-color: transparent;
  border-radius: 0;
  margin: 0;
  padding: 0;
}

*:focus {
  outline: none;
}

.calculator {
  width: 100%;
  max-width: 40rem;
  border: none;
  background: #000;
}

.display {
  padding: 1.5rem 1.5rem;
  text-align: right;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  background-color: #000;
  font-size: 4rem;
  color: #fff;
  line-height: 1;
}

.buttons {
  display: flex;
  flex-flow: row wrap;
  width: 100%;
}

.buttons button {
  transition: background 200ms ease, color 200ms ease;
  flex: 0 0 25%;
  line-height: 5rem;
  border: none;
  border-top: 1px solid #000;
  border-right: 1px solid #000;
  color: #fff;
  font-size: 2.5rem;
  background-color: #424242;
}

.buttons button:active {
  background-color: #626262;
}

.buttons button:nth-child(4n+4) {
  background-color: #f09214;
  border-right: none;
}

.buttons button:nth-child(4n+4):active {
  background-color: #f7a434;
}

.buttons button.is-active {
  background-color: #fff;
  color: #f09214;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将两个字符串当作数字相加?

使用React native EXPO时如何将数字格式化为货币?

如何将React用作外部包

React:如何将React组件注入体内?

如何将文件中的数字相加到计算中?

如何使用React.js动态获取标签值并将不同输入的数字相加

React Calculator:如何防止多个小数?

如何将React与Django连接?

如何将api中的值另存为数字REACT js

React js Calculator的最终结果显示在console.log中,但不在浏览器中

如何使用rvest来获取从Lux到Lumens Calculator的动态数据

如何将一个数组中的一组数字相加?

如何将通过比较日期和公司而找到的数字相加?

如何将jQuery与React js集成?

如何用deb替换Snap应用程序,例如Gnome Calculator?

如何将 PatientName 与 7 天内的小时数相加(如果超过 9)

如何将数字 1 到“n”相加并打印出结果?

Microsoft Calculator 中两个数字相加的代码在哪里?

如何将标签中的数字相加

如何将 Jquery 导入 React

如何将图像插入状态(React)

如何将 React 形式转换为 React Native

熊猫:如何将值相加,前提是它们的数字相同

如何将 OR 之间的所有数字相加?

React Calculator 中的复选框

当数字为文本形式时,如何将单元格相加?

React JS 如何将单个函数添加到数字输入箭头?

如何将循环中的所有数字相加

React JS - 如何将数字从每分钟 1 分钟增加到 9 分钟?