【发布时间】: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,所以我会卡在 1,永远不会回到零。
using react:jsfiddle
使用 onClick() 计数器从 0 上升到 2;
计数器:0 1 2
点击同一个 onClick() 按钮,每次点击计数器都会从 2 减回到 0。
计数器:2 1 0;
【问题讨论】:
标签: javascript reactjs
仅使用计数,没有逻辑方法来确定增量或减量。您可以在状态跟踪增量与减量中添加一个布尔值。
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,
});
}
【讨论】:
onClick(e) {
let tmp = this.state.count;
tmp++;
if(tmp > 2){
tmp = 0;
}
this.setState({
count: tmp
})
}
我认为这不是最佳答案,但它会激励你。
【讨论】:
你能看看这个例子吗: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: '+'
});
}
}
}
【讨论】: