【问题标题】:How to increment counter value for each dropdown selection如何为每个下拉选择增加计数器值
【发布时间】:2019-06-12 04:14:08
【问题描述】:

我正在尝试根据下拉菜单中的某些选项选择来增加 反应状态计数器。问题是我想保留计数器值并根据选择"Test"等条件不断增加。

如果在两个下拉菜单中都选择了"Test",我将使用下面的代码来增加计数器

{this.state.DownloadPrepare == "Test" ? this.state.Identify == "Test" : this.state.CalcNoOfObs+1}

【问题讨论】:

  • 您遇到了什么问题?

标签: javascript reactjs counter


【解决方案1】:

您可能正在寻找这样的东西:https://codesandbox.io/s/zealous-shirley-flznm

class App extends React.Component {
  state = {
    counter: 0,
    listOne: null,
    listTwo: null
  };

  incrementIfTest = event => {
    console.log(event.target.name);

    if (
      //check if is already selected, do not want to double count
      event.target.value === "Test" &&
      this.state[event.target.name] !== "Test"
    ) {
      //increment count
      this.setState({
        ...this.state,
        counter: this.state.counter + 1,
        [event.target.name]: event.target.value
      });
      //decrease count if they remove Test selection, cannot be below 0.
    } else if(this.state[event.target.name] === "Test"){
      this.setState({
        ...this.state,
        counter: this.state.counter > 0 ? this.state.counter - 1 : 0,
        [event.target.name]: event.target.value
      });
    }
  };

  render() {
    return (
      <div>
        <h4>{this.state.counter}</h4>
        <select name="listOne" onChange={this.incrementIfTest}>
          <option />
          <option>DownloadPrepare</option>
          <option>Test</option>
        </select>
        <select name="listTwo" onChange={this.incrementIfTest}>
          <option />
          <option>DownloadPrepare</option>
          <option>Test</option>
        </select>
      </div>
    );
  }
}

利用下拉列表中的onChange() 事件监听器(选择标签)。我们可以传入事件并通过event.target.value 访问选定的选项。如果它等于Test,我们只需增加count

【讨论】:

  • 太棒了!非常欢迎您@Snehal。快乐编码:)
【解决方案2】:

我为点击制作了一个脚本,您也可以对更改进行操作,希望对您有用。

谢谢

constructor(props) {
    super(props);
    this.state = {
      DownloadPrepare: "Test",
      Identify: "",
      CalcNoOfObs: 0
    };
  }

click() { // make your function what you want on change 
    this.state.DownloadPrepare == "Test"
      ? this.setState({
          Identify: "Test"
        })
      : this.setState({
          CalcNoOfObs: this.state.CalcNoOfObs + 1
        });
  }



<button onClick={() => this.click()}>click</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多