停止上一个和下一个按钮增量某个值 - ReactJS

问题描述 投票:1回答:1

有一个小脚本编码,当点击上一个和下一个按钮时,它会向左或向右递增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>
javascript reactjs
1个回答
3
投票

设置状态时,您可以使用Math.maxMath.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)
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.