Gab*_*flo 2 typescript reactjs swiper.js
我正在尝试在我的项目中的 Typescript 文件中使用 Swiperjs。我想从另一个组件更改活动幻灯片(选项卡,来自材料 UI,已经就位)。我可以直接在 Swiper 组件中滑动,但我希望在其他地方和其他地方也能实现这一点。
但是我没有找到在组件外部触发该方法slideTo(此处为API)的方法
...
<Swiper
onSlideChange={(swiper) => setValue(swiper.realIndex)}
...
>
Here my slides, other components, ...
</Swiper>
Run Code Online (Sandbox Code Playgroud)
所以理想情况下我宁愿有这样的东西:
...
function handleExternalChangeSlide=(newSlideIndexToShow)=>{
swiper.slidesTo(newSlideIndexToShow)
}
<Swiper
onSlideChange={(swiper) => setValue(swiper.realIndex)}
...
>
Here my slides, other components, ...
</Swiper>
Run Code Online (Sandbox Code Playgroud)
我见过很多人这样做:
var swiper = new Swiper('.swiper-container', {
... options
});
function handleExternalChangeSlide=(newSlideIndexToShow)=>{
swiper.slidesTo(newSlideIndexToShow)
}
)
Run Code Online (Sandbox Code Playgroud)
但实际上,Typescript 声称:只能使用“new”关键字调用 void 函数,我不知道如何处理它
您是否看到任何方法可以继续在我的 .tsx 文件中的 Swiper 组件之外更改活动幻灯片(不使用 Swiper 的分页)?
该Swiper组件采用onSwiperprops 一个函数,该函数将返回创建的 Swiper 的实例。您可以将此实例保存到 a 中state,然后调用它所需的所有方法。
这是实现选项之一:
const [swiperInstance, setSwiperInstance] = useState<SwiperCore>();
const handleExternalChangeSlide = (newSlideIndexToShow) => {
swiperInstance.slidesTo(newSlideIndexToShow);
}
...
<Swiper
onSwiper={setSwiperInstance}
onSlideChange={(swiper) => setValue(swiper.realIndex)}
...
>
Here my slides, other components, ...
</Swiper>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9241 次 |
| 最近记录: |