开发者问题收集

Swiper React 无法将 undefined 或 null 转换为对象

2022-07-20
5195

我正在使用 Swiper 库来显示图片幻灯片和缩略图。每当我点击某个缩略图时,映射到所点击缩略图的图片就会出现在视图中。

import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, Thumbs } from "swiper";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/thumbs";
import "./swiper.css";
const SwiperImage = () => {
  const [activeThumb, setActiveThumb] = React.useState();
  return (
    <>
      <Swiper
        loop={true}
        spaceBetween={10}
        navigation={true}
        modules={[Navigation, Thumbs]}
        grabCursor={true}
        thumbs={{ swiper: activeThumb }}
        className="vehicle-image-slider"
      >
        {images.map((item, index) => (
          <SwiperSlide key={index}>
            <img src={item} alt="lamborgini image" />
          </SwiperSlide>
        ))}
      </Swiper>
      <Swiper
        onSwiper={setActiveThumb}
        loop={true}
        spaceBetween={10}
        slidesPerView={4}
        modules={[Navigation, Thumbs]}
        className="vehicle-image-slider-thumbs"
      >
        {images.map((item, index) => (
          <SwiperSlide key={index}>
            <div className="thumbs-wrapper">
              <img src={item} alt="lamborgini image" />
            </div>
          </SwiperSlide>
        ))}
      </Swiper>
    </>
  );
};

我尝试使用 onSwiper prop 来实现此功能,但遇到了错误。

thumbs.js:67 Uncaught TypeError: Cannot convert undefined or null to object
    at Function.assign (<anonymous>)
    at Object.init (thumbs.js:67:1)
    at updateSwiper (update-swiper.js:92:1)
    at swiper.js:158:1
    at commitHookEffectLi

根据文档,我似乎找不到我的代码有什么问题。

2个回答

添加此项。

thumbs={{swiper: thumbsSwiper && !thumbsSwiper.destroyed ? thumbsSwiper : null}}
Lope
2022-07-29

我使用

import {SwiperClass } from "swiper/react"
const [thumbsSwiper, setThumbsSwiper] = React.useState<SwiperClass>()
修复了此问题
Usama Sajjad
2024-02-06