首页 > 解决方案 > 如何在 reactjs 项目的引导程序 5 中停止在轮播中的最后一个滑块图像上滑动

问题描述

请在 js 中告诉我,比如我如何在 react js 项目中的最后一张图片上停止滑动这是我的滑块代码,我想删除下一个和上一个图标,并且还想在滑块到达 IMG src={slider5} 时停止滑块. 请帮我找到这个答案

const Slider = () => {
  const prevSlideHandler = () => {
    console.log("clicked");
    NotificationManager.error("You have rejected the image", "Rejected!", 1000);
  };

  const nextSlideHandler = () => {
 

    NotificationManager.success("You have Liked the image", "Success", 1000);
  };

  return (
    <section>
      <div
        id="carouselExampleIndicators"
        class="carousel slide"
        data-bs-ride="carousel"
        data-wrap="false"
        data-interval="false"
      >
       
          <div class="carousel-item">
            <img src={slider4} class="d-block w-100" alt="..." />
          </div>

          <div class="carousel-item" id="lastSlider">
            <img src={slider5} class="d-block w-100" alt="..." />
          </div>
          {/* <div class="carousel-item">
            <img src={slider5} class="d-block w-100" alt="..." />
          </div> */}
        </div>
        <button
          class="carousel-control-prev"
          type="button"
          data-bs-target="#carouselExampleIndicators"
          data-bs-slide="prev"
          onClick={prevSlideHandler}
        >
          <span class="carousel-control-prev-icon" aria-hidden="true"></span>
          <span class="visually-hidden">Previous</span>
        </button>
        <button
          class="carousel-control-next"
          type="button"
          data-bs-target="#carouselExampleIndicators"
          data-bs-slide="next"
          onClick={nextSlideHandler}
        >
          <span
            class="carousel-control-next-icon myarrow"
            aria-hidden="true"
          ></span>
          <span class="visually-hidden">Next</span>
        </button>
      </div>
    </section>
  );
};

export default Slider;

标签: reactjscarouselbootstrap-5

解决方案


您应该有一个状态变量来跟踪用户在轮播中的当前图像,我们称之为“计数器”。单击下一步时它会增加,单击上一个时它会减少。

  const prevSlideHandler = () => {
    console.log("clicked");
    NotificationManager.error("You have rejected the image", "Rejected!", 1000);
    this.setState((state, props) => ({
       counter: state.counter += 1
    }));
  };

  const nextSlideHandler = () => {
 

    NotificationManager.success("You have Liked the image", "Success", 1000);
    this.setState((state, props) => ({
       counter: state.counter -= 1
    }));
  };

当用户到达图像的末尾时,计数器应该等于轮播中的图像数量。发生这种情况时,您应该使用这样的三元运算符隐藏下一个按钮:

      {
      counter != [carousel_images].length? 
        <button
          class="carousel-control-next"
          type="button"
          data-bs-target="#carouselExampleIndicators"
          data-bs-slide="next"
          onClick={nextSlideHandler}
        >
          <span
            class="carousel-control-next-icon myarrow"
            aria-hidden="true"
          ></span>
          <span class="visually-hidden">Next</span>
        </button>
}

推荐阅读