如何用一位数字替换0内部输入?

时间:2018-11-18 21:50:51

标签: javascript reactjs

我正在尝试创建一个计算器。如何删除显示屏中输入数字的初始状态0?我输入的第一个数字应为4,显示屏显示04。我不确定如何删除前面的0。输入数字时,我应该可以看到输入的数字从0开始。

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      operations: [0]
    }
    this.handleClick = this.handleClick.bind(this);
  }

  //calculation method
  calculateOperations() {
    let result = this.state.operations.join('');
    if(result) {
      result = math.eval(result);
      result = math.format(result, { precision: 14 });
      result = String(result);
      this.setState({
        operations: [result]
      });
    }
  }

  handleClick(e) {
    const value = e.target.getAttribute('data-value');
    switch(value) {
      case 'clear':
        this.setState({
          operations: [0]
        });
        break
      case '=':
        this.calculateOperations();
        break
      default:
        //creates new array with input digits
        const newOperations = [...this.state.operations, value];
        this.setState({
          operations: newOperations
        });
        break
    }
  }

  render() {
    return (
      <div className="container">
        <Display data={this.state.operations} />
        <Buttons>
          <Button onClick={this.handleClick} id='clear' label='AC' value='clear'/>
          <Button onClick={this.handleClick} id='seven' label='7' value='7'/>
          <Button onClick={this.handleClick} id='four' label='4' value='4' />
          <Button onClick={this.handleClick} id='one' label='1' value='1' />
          <Button onClick={this.handleClick} id='zero' lable='0' value='0' />

          <Button onClick={this.handleClick} id='divide' label='/' value='/' />
          <Button onClick={this.handleClick} id='eight' label='5' value='5' />
          <Button onClick={this.handleClick} id='five' label='8' value='8' />
          <Button onClick={this.handleClick} id='two' label='2' value='2' />
          <Button onClick={this.handleClick} id='decimal' label='.' value='.' />

          <Button onClick={this.handleClick} id='multiply' label='x' value='*' />
          <Button onClick={this.handleClick} id='nine' label='9' value='7' />
          <Button onClick={this.handleClick} id='six' label='6' value='6' />
          <Button onClick={this.handleClick} id='three' label='3' value='3'/>
          <Button label='' value='null' />

          <Button onClick={this.handleClick} id='subtract' label='-' value='-' />
          <Button onClick={this.handleClick} id='add' label='+' value='+' size='2' />
          <Button onClick={this.handleClick} id='equals' label='=' value='=' size='2'/>
        </Buttons>
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:1)

您可以在handleClick中执行一些逻辑,即如果该数组仅包含0,则将其替换为仅包含输入值的新数组,但是我会考虑采用另一种方法。我认为开头的0是占位符,而不是操作,而是将operations初始化为[],然后让您的Display组件对props.data.length === 0有特殊情况会呈现0。这将使您handleClick中的逻辑保持简单,无需检查特殊值。