SwiperJS 文档 显示 导航 prevEl/nextEl 可以是 "string" 或 "HTMLElement" 类型。使用字符串选择器很容易,如:
const MySwiper = (props) => (
<Swiper
navigation={{
prevEl: '.prev',
nextEl: '.next',
}}
{...props}
>
<SwiperSlide>slide 1</SwiperSlide>
<SwiperSlide>slide 2</SwiperSlide>
<div className="prev" />
<div className="next" />
</Swiper>
)
然而,如何在React引用中正确实现这一点?使用HTML节点而不是字符串选择器使得导航prevEl/nextEl仅限于每个渲染的MySwiper
实例。
const App = () => (
<div>
<MySwiper className="mySwiper1" />
<MySwiper className="mySwiper2" />
</div>
)
在上面的应用程序示例中,从.mySwiper2
导航prevEl/nextEl不应该触发.mySwiper1
的滑动,这是使用字符串选择器会发生的情况。我当前的悲伤和hacky解决方法:
const MySwiper = () => {
const navigationPrevRef = React.useRef(null)
const navigationNextRef = React.useRef(null)
return (
<Swiper
navigation={{
// Both prevEl & nextEl are null at render so this does not work
prevEl: navigationPrevRef.current,
nextEl: navigationNextRef.current,
}}
onSwiper={(swiper) => {
// Delay execution for the refs to be defined
setTimeout(() => {
// Override prevEl & nextEl now that refs are defined
swiper.params.navigation.prevEl = navigationPrevRef.current
swiper.params.navigation.nextEl = navigationNextRef.current
// Re-init navigation
swiper.navigation.destroy()
swiper.navigation.init()
swiper.navigation.update()
})
}}
>
<SwiperSlide>slide 1</SwiperSlide>
<SwiperSlide>slide 2</SwiperSlide>
<div ref={navigationPrevRef} />
<div ref={navigationNextRef} />
</Swiper>
)
}