有一个小脚本编码,当点击上一个和下一个按钮时,它会向左或向右递增100px。
想知道是否有一种方法可以使脚本在达到某个点后停止增加值(例如,例如-500px或+ 500px)。
constructor(props) {
super();
this.state = {
bgColor: 0
};
this.handleClickRight = this.handleClickRight.bind(this);
this.handleClickLeft = this.handleClickLeft.bind(this);
}
handleClickRight(e) {
e.preventDefault();
this.setState({
bgColor: this.state.bgColor - 100
})
}
handleClickLeft(e) {
e.preventDefault();
this.setState({
bgColor: this.state.bgColor + 100
})
}
render() {
return (
<div>
<div className="slider-controls">
<a href="#" className="slider-control prev" onClick={this.handleClickLeft}>Prev</a>
<a href="#" className="slider-control next" onClick={this.handleClickRight}>Next</a>
</div>
设置状态时,您可以使用Math.max
和Math.min
。同时检查该值是否已经是最小值或最大值,以避免不必要的重新渲染:
handleClickRight(e) {
e.preventDefault();
const { bgColor } = this.state;
if (bgColor !== -500) this.setState({
bgColor: Math.max(bgColor - 100, -500)
})
}
handleClickLeft(e) {
e.preventDefault();
const { bgColor } = this.state;
if (bgColor !== 500) this.setState({
bgColor: Math.min(bgColor + 100, 500)
})
}