next.js 如何修复“TypeError:Swiper.initialize is not a function”在使用TypeScript的React Swiper中的错误

ngynwnxp  于 2023-11-18  发布在  TypeScript
关注(0)|答案(2)|浏览(162)

我尝试在nextJs和Typescript中使用swiper。我想用injectStyle编辑样式,但我得到了一个关于初始化的错误,但我不知道如何修复它。

import { useRef, useEffect } from "react";
import { register } from "swiper/element/bundle";
register();

const swiperRef: any = useRef(null);

useEffect(() => {
const Swiper = swiperRef.current;
Object.assign(Swiper, {
  modules: [Pagination],
  injectStyles: [
    `
    .swiper-horizontal > .swiper-pagination-bullets,
    .swiper-pagination-bullets .swiper-pagination-horizontal,
    .swiper-pagination-custom,
    .swiper-pagination-fraction {
      bottom: var(--swiper-pagination-bottom, 8px);
      top: var(--swiper-pagination-top, 220px) !important;
      left: 0;
      width: 100%;
    }

    .swiper,
    swiper-container {
      overflow: visible !important;
    }

    .swiper-pagination-bullet-active {
      background: var(--swiper-pagination-color, #475aea) !important;
    }

    .swiper-pagination-bullet {
      background: var(
        --swiper-pagination-bullet-inactive-color,
        #475aea
      ) !important;
    }
    `,
  ],
});
Swiper.initialize();  <-- Error Here
}, []);

字符串
在render中:

<Swiper
  ref={swiperRef}
  init={false}
  pagination={true}
  modules={[Pagination]}
  className="mySwiper"
> ... </Swiper>


我试着用Swiper Element帮助修复它,但我不能. https://swiperjs.com/element#usage-with-react

a8jjtwal

a8jjtwal1#

为我工作

const swiperRef = useRef<HTMLLinkElement | any>(null);

    useEffect(() => {

      // Register Swiper web component
      register();
  
      if (swiperRef.current) {
        // Add event listener
        swiperRef.current.addEventListener('slidechange', (e: any) => {
          console.log(e.detail);
        });
    
        // Object with parameters
        const params = {
          // or pass it in on
          on: {
            slideChange(s) {
              console.log(s);
            },
          },
        };
    
        // Assign it to swiper element
        Object.assign(swiperRef.current!, params);
    
        // initialize swiper
        swiperRef.current.initialize();
      }

  });

字符串

dgiusagp

dgiusagp2#

我使用这个接口来修复一个错误:

import { SwiperContainer } from 'swiper/element/bundle';

const swiperRef = useRef<SwiperContainer>(null);

字符串

相关问题