reactjs 如何改变幻灯片透视按钮点击和屏幕大小的变化与Swiper.js和React?

x33g5p2x  于 2023-01-12  发布在  React
关注(0)|答案(1)|浏览(100)

我想实现一个按钮,可以改变slidesPerView的数量。布局的屏幕截图:

例如,当我单击5时,slidesPerView的编号变为5,如何实现这一点?
我试过用这种方式实现它,但没有成功:

const slidesPerViewOptions = [3, 5, 7]

const changeSlidesPerView = (option: number) => {
  swiperRef.params.slidesPerView = option
}

<div>
  {slidesPerViewOptions.map((option) => (
    <button
      key={option}
      onClick={() => changeSlidesPerView(option)}
    >
      {option}
    </button>
  ))}
</div>
fbcarpbf

fbcarpbf1#

为了正确的重新渲染,我会使用一个名为slidePerview的状态,下面是一个设置的例子:

const [slidePerview, setSlidePerview] = useState(1);

const changeSlidesPerView = (option) => {
  setSlidePerview(option);
};
<Swiper
  slidesPerView={slidePerview}
  ....

如果你还想根据屏幕尺寸的变化来更新它,

useEffect(() => {
  const checkScreenSize = () => {
    if (window.innerWidth < 750) {
      setSlidePerview(1);
    } else if (window.innerWidth < 1080) {
      setSlidePerview(3);
    } else {
      setSlidePerview(5);
    }
  };
  window.addEventListener("resize", checkScreenSize);
  return () => window.removeEventListener("resize", checkScreenSize);
}, []);

相关问题