我正尝试根据下拉菜单中的某些选项来增加反应状态计数器。问题是我想保留计数器值并根据选择了选项"Test"
之类的条件连续递增。
如果在两个下拉列表中都选择了"Test"
,我将使用下面的代码来递增计数器
{this.state.DownloadPrepare == "Test" ? this.state.Identify == "Test" : this.state.CalcNoOfObs+1}
答案 0 :(得分:0)
您可能正在寻找类似以下的内容: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
答案 1 :(得分:0)
我为单击创建了一个脚本,您也可以进行更改,我希望它对您有用。
谢谢
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>