【发布时间】:2020-09-28 09:23:23
【问题描述】:
SwiperJS documentation 声明导航 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 refs 正确实现这一点?使用 HTML 节点而不是字符串选择器允许将导航 prevEl/nextEl 范围限定为 MySwiper 的每个渲染实例。
const App = () => (
<div>
<MySwiper className="mySwiper1" />
<MySwiper className="mySwiper2" />
</div>
)
在上面的 App 示例中,.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>
)
}
【问题讨论】: