【问题标题】:using the same onClick button increment counter up to 2 (range 0-2) and then decrement back to 0 from 2使用相同的 onClick 按钮将计数器递增到 2(范围 0-2),然后从 2 递减回 0
【发布时间】:2023-03-31 15:28:01
【问题描述】:

我在逻辑上执行此操作时遇到了麻烦。我的计数会递减和递增 1,所以我会卡在 1,永远不会回到零。

using react:jsfiddle

使用 onClick() 计数器从 0 上升到 2;

计数器:0 1 2

点击同一个 onClick() 按钮,每次点击计数器都会从 2 减回到 0。

计数器:2 1 0;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    仅使用计数,没有逻辑方法来确定增量或减量。您可以在状态跟踪增量与减量中添加一个布尔值。

    onClick(e) {
      let count = this.state.increment ? this.state.count + 1 : this.state.count - 1;
    
      let increment = this.state.increment;
    
      if (count === 0) {
        increment = true;
      } else if (count >= 2) {
        increment = false;
      }
    
      this.setState({
        count,
        increment,
      });
    }
    

    https://jsfiddle.net/69z2wepo/264102/

    【讨论】:

      【解决方案2】:
      onClick(e) {
        let tmp = this.state.count;
        tmp++;
        if(tmp > 2){
          tmp = 0;
        }
        this.setState({
          count: tmp
        })
      }
      

      我认为这不是最佳答案,但它会激励你。

      【讨论】:

        【解决方案3】:

        你能看看这个例子吗:jsfiddle

         onClick(e) {
        
        
          if(this.state.action == '+') {
             this.setState({
                count: this.state.count + 1
            });
          } else {
             this.setState({
               count: this.state.count - 1
             });
          }
        
          if(this.state.count == 1) {
              if( this.state.action == '+') {
        
                this.setState({
                    action: '-'
                });
              } else {
                this.setState({
                    action: '+'
                });
              }
          }
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-06-22
          • 1970-01-01
          • 1970-01-01
          • 2020-05-08
          • 1970-01-01
          • 2015-04-21
          • 1970-01-01
          相关资源
          最近更新 更多