如何为每个下拉选择增加计数器值

How to increment counter value for each dropdown selection

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

如果在下拉列表

中都选择了"Test",我将使用下面的代码来增加计数器
{this.state.DownloadPrepare == "Test" ? this.state.Identify == "Test" : this.state.CalcNoOfObs+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>
    );
  }
}

在下拉菜单(select 标签)上使用 onChange() event-listener。我们可以传入事件并通过 event.target.value 访问 selected 选项。如果它等于 Test,我们只需增加 count

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

谢谢

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>