You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Next.js中使用带缩略图的Swiper时遇到TypeScript类型错误

在Next.js中解决Swiper缩略图组件的TypeScript类型错误

你遇到的问题是因为onSwiper回调传递的SwiperRef类型和useState的状态类型未正确对齐,直接传setThumbsSwiper会触发TS的类型校验报错。按以下步骤修复:

  1. 导入正确的类型
    从swiper/react库中明确导入SwiperRef类型:

    import { Swiper, SwiperSlide, SwiperRef } from 'swiper/react';
    import 'swiper/css';
    import 'swiper/css/thumbs';
    
  2. 正确声明useState的类型
    给useState指定泛型类型为SwiperRef | null,明确状态可以是Swiper实例或者null:

    const [thumbsSwiper, setThumbsSwiper] = useState<SwiperRef | null>(null);
    
  3. 显式处理onSwiper回调
    不要直接传递setThumbsSwiper,用箭头函数包裹并显式指定参数类型,确保和SwiperRef匹配:

    {/* 缩略图Swiper */}
    <Swiper
      onSwiper={(swiper: SwiperRef) => setThumbsSwiper(swiper)}
      spaceBetween={10}
      slidesPerView={4}
      freeMode={true}
      watchSlidesProgress={true}
    >
      <SwiperSlide><img src="/thumb-1.jpg" alt="缩略图1" /></SwiperSlide>
      <SwiperSlide><img src="/thumb-2.jpg" alt="缩略图2" /></SwiperSlide>
      {/* 更多缩略图Slide */}
    </Swiper>
    
    {/* 主内容Swiper */}
    <Swiper
      spaceBetween={10}
      thumbs={{ swiper: thumbsSwiper }}
    >
      <SwiperSlide><img src="/main-1.jpg" alt="主图1" /></SwiperSlide>
      <SwiperSlide><img src="/main-2.jpg" alt="主图2" /></SwiperSlide>
      {/* 更多主内容Slide */}
    </Swiper>
    

之前修改useState类型没用,大概率是没正确导入SwiperRef类型,或是未显式处理回调参数类型导致TS无法正确推断。

内容的提问来源于stack exchange,提问作者Enpeiks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 09:50:36