代码之家  ›  专栏  ›  技术社区  ›  StackUnderFlow

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

  •  1
  • StackUnderFlow  · 技术社区  · 6 年前

    得到了一个小脚本编码的增量左或右100像素时,点击上一步和下一步按钮。

    我想知道是否有一种方法可以使脚本在达到某个点时停止增加值(例如-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>
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   CertainPerformance    6 年前

    你可以用 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)
      })
    }