开发者问题收集

在 TypeScript 中使用 Swiper:TypeError:如果没有“new”,则无法调用类构造函数 Swiper

2022-07-20
8072

我找不到任何可以解决这个问题的方法,所以我会尝试一下(这是我的第一次尝试)。 我正在使用 TypeScript 和 Next.js,尽管 Swiper 没有直接支持 Next.js 和 TS。

TypeScript 中的代码:

import { Box } from '@chakra-ui/react';
import React from 'react';
import { SwiperSlide } from 'swiper/react';
import Swiper, { FreeMode, Pagination } from 'swiper';
import SwiperCard from './SwiperCard';
import 'swiper/css';
import 'swiper/css/free-mode';
import 'swiper/css/pagination';

const swiper = new Swiper('.swiper', {
// configure Swiper to use modules
modules: [FreeMode, Pagination],

// Optional parameters
direction: 'horizontal',
loop: true,

// If we need pagination
pagination: {
  clickable: true,
},

  slidesPerView: 3,
  spaceBetween: 30,
  freeMode: true,
});

export default function FrontSwipe() {
return (
  <Box>
    <Swiper>
      <SwiperSlide>
        <SwiperCard>1</SwiperCard>
      </SwiperSlide>
    </Swiper>
  </Box>
 );
}

我收到以下错误:

TypeError: Class constructor Swiper cannot be invoked without 'new'

另外还显示了以下问题:

'Swiper' cannot be used as a JSX component.
 Its instance type 'Swiper' is not a valid JSX element.
 Type 'Swiper' is missing the following properties from type 'ElementClass': render, context, setState, forceUpdate, and 3 more.ts(2786)

提前致谢!

2个回答

尝试从“swiper/react”导入 Swiper Docs

从“swiper/react”导入 { Swiper };

但看起来你可能会遇到一些名称冲突,也许:

从“swiper/react”导入 { Swiper as SwiperComponent };

export default function FrontSwipe() {
return (
  <Box>
    <SwiperComponent>
      <SwiperSlide>
        <SwiperCard>1</SwiperCard>
      </SwiperSlide>
    </SwiperComponent>
  </Box>
 );
}
Eduards Egle
2022-07-20

我知道在 9.4.1 上可以运行的版本在 10.0.4 上无法运行,因为从“swiper”导入了 { Pagination }

这是运行的代码

// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/css";
import "swiper/css/pagination";

// import required modules
import { Pagination }  from "swiper";

export default function Page(){
    return(
    <Swiper
    pagination={{ dynamicBullets: true }}
    modules={[Pagination]}
    >
    {[0, 6, 12].map((start, slideIndex) => (
        <SwiperSlide key={slideIndex}>
            <div className="grid grid-cols-2 gap-3 pb-10">
                {topSearch.slice(start, start + 6).map((keyword, index) => (
                    <SwiperSlideContent key={`sliderContent${keyword}`} keyword={keyword} index={index + start} />
                ))}
            </div>
        </SwiperSlide>
    ))}
    </Swiper>
)
}
Yijun Kim
2023-07-11