Tsx version of Swiper for React was released in summer 2020. Repeating the example of the official documentation, the slider breaks - even the styles refuse to work.
The main task is to add thumbs to the slider and link them. This means that you need to install the controller and thumbs modules, and then use the onSwiper method to specify who is attached to whom.
So, we expect this result (here without any binding to each other):
Expected screenshot
But we've got this:
Incorrect screenshot
The only difference between them is that I do not call onSwipe={setMainSwiper}
and onSwipe={setThumbSwiper}
in the working version, where setNameSlider are useState()
hooks. Of course, incorrect version doesn't work at all.
Code examples:
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>
And from official documentation:
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>
)
}
question from:
https://stackoverflow.com/questions/65921778/saving-swiper-instance-via-react-hooks 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…