React 中的 Swiperjs:swiper.slideTo TypeScript

Swiperjs in React : swiper.slideTo TypeScript

我正在尝试在我的项目中的 Typescript 文件中使用 Swiperjs。我想从另一个组件更改活动幻灯片(选项卡,来自 material UI,已经到位)。我可以直接在 Swiper 组件中滑动,但我希望在其他地方和其他地方也能做到这一点。

但是我没有找到在组件外触发方法slideTohere API)的方法

...
<Swiper
   onSlideChange={(swiper) => setValue(swiper.realIndex)}
   ...
> 
Here my slides, other components, ...
</Swiper>

所以理想情况下,我宁愿有这样的东西:

...

function handleExternalChangeSlide=(newSlideIndexToShow)=>{
   swiper.slidesTo(newSlideIndexToShow)
}

<Swiper
   onSlideChange={(swiper) => setValue(swiper.realIndex)}
   ...
> 
Here my slides, other components, ...
</Swiper>

我见过很多人这样做:

var swiper = new Swiper('.swiper-container', {
  ... options
});

function handleExternalChangeSlide=(newSlideIndexToShow)=>{
   swiper.slidesTo(newSlideIndexToShow)
}
)

但实际上,Typescript 声称:只能使用 'new' 关键字调用 void 函数,我不知道如何处理它

您是否看到任何方法可以继续更改我的 .tsx 文件中 Swiper 组件外部的活动幻灯片(不使用 Swiper 的分页)?

Swiper 组件采用 onSwiper 支持一个函数,该函数将 return 您创建的 Swiper 的实例。 您可以将此实例保存到 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>