通过 React Hooks 保存 Swiper 实例

Tsx 版本的 Swiper for React 于 2020 年夏季发布。重复官方文档的示例,滑块坏了 - 甚至样式都拒绝工作。

主要任务是将拇指添加到滑块并链接它们。这意味着您需要安装控制器和拇指模块,然后使用 onSwiper 方法指定谁附加到谁。

所以,我们期望这个结果(这里没有任何相互绑定): Expected screenshot

但是我们有这个: Incorrect screenshot

它们之间的唯一区别是我在工作版本中不调用 onSwipe={setMainSwiper}onSwipe={setThumbSwiper} ,其中 set Name Slider 是 useState() 钩子。当然,不正确的版本根本不起作用。

代码示例:

import SwiperCore, { Autoplay, Controller, Lazy, Thumbs } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperClass from 'swiper/types/swiper-class';

SwiperCore.use([Autoplay, Controller, Lazy, Thumbs]);

...

const [mainSwiper, setMainSwiper] = useState<SwiperClass>();
const [thumbsSwiper, setThumbsSwiper] = useState<SwiperClass>();

...

<Swiper
  spaceBetween={0}
  slidesPerView={1}
  preloadImages={false}
  onSwiper={setMainSwiper}
  thumbs={{ swiper: thumbsSwiper }}
  controller={{ control: thumbsSwiper }}
  autoplay
  loop
  lazy
>
  {state?.Images.map(image => (
    <SwiperSlide key={uniqid()} className={styles.medium}>
      {getSlide('medium', image.Medium)}
    </SwiperSlide>
  ))}
</Swiper>

<Swiper
  spaceBetween={3}
  slidesPerView={5}
  preloadImages={false}
  onSwiper={setThumbsSwiper}
  controller={{ control: mainSwiper }}
  slideToClickedSlide
  watchSlidesVisibility
  watchSlidesProgress
  lazy
>
  {state?.Images.map(image => (
    <SwiperSlide key={uniqid()} className={styles.small}>
      {getSlide('small', image.Small)}
    </SwiperSlide>
  ))}
</Swiper>

并且来自官方文档:

import SwiperCore, { Thumbs } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';

// install Swiper's Thumbs component
Swiper.use([Thumbs]);

const App = () => {
  // store thumbs swiper instance
  const [thumbsSwiper, setThumbsSwiper] = useState(null);

  return (
    <main>
      {/* Main Swiper -> pass thumbs swiper instance */}
      <Swiper thumbs={{ swiper: thumbsSwiper }} ...>
        {/* ... */}
      </Swiper>

      {/* Thumbs Swiper -> store swiper instance */}
      {/* It is also required to set watchSlidesVisibility and watchSlidesProgress props */ }
      <Swiper
        onSwiper={setThumbsSwiper}
        watchSlidesVisibility
        watchSlidesProgress
        ...
      >
        {/* ... */}
      </Swiper>
    </main>
  )
}
stack overflow Saving Swiper instance via React Hooks
原文答案

答案:

作者头像

我也有同样的问题尝试更改您的代码

const [thumbsSwiper, setThumbsSwiper] = useState(null);

至:

const [thumbsSwiper, setThumbsSwiper] = useState<SwiperCore>();