轮播图---swiper

import React, { useState } from "react";
import SwiperCore, { Autoplay, Pagination } from "swiper";
import { Swiper, SwiperSlide } from "swiper/react/swiper-react.js";

import "swiper/swiper.scss";
import "swiper/modules/navigation/navigation.scss";
import "swiper/modules/pagination/pagination.scss";
import styles from "./index.module.scss";

SwiperCore.use([Autoplay, Pagination]);

interface PropsType {
  children: Array<JSX.Element>;
  className?: string;
  swiperConfig?: any;
  accessoryRenderer?: (data: { curIndex: number }) => JSX.Element;
  onSlideDone?: (e) => void;
}
export default (props: PropsType) => {
  const [sliderIndex, setSliderIndex] = useState(0);

  const {
    children,
    className = "",
    swiperConfig = {},
    accessoryRenderer,
    onSlideDone,
  } = props;

  const swiperConfigResult = Object.assign(
    {
      autoplay: false,
      // autoplay:false,
      spaceBetween: 1,
      loop: false,
      allowTouchMove: true,
      noSwiping: true,
      pagination:
        children.length > 1
          ? { el: ".swiper-pagination", clickable: true }
          : false,
    },
    swiperConfig
  );

  return (
    <div className={"service-carousel " + className}>
      <Swiper
        {...swiperConfigResult}
        onSlideChange={(slide) => {
          setSliderIndex(slide.realIndex);
          if (onSlideDone) {
            slide.realIndex === 1 ? onSlideDone(1) : onSlideDone(0);
          }
        }}
      >
        {props.children.map((item, index) => {
          return <SwiperSlide key={index}>{item}</SwiperSlide>;
        })}
        {children.length > 1 && (
          <div
            className={[styles.swiperPagination, "swiper-pagination"].join(" ")}
          ></div>
        )}
      </Swiper>

      {/* 辅助渲染下标的 */}
      {accessoryRenderer ? accessoryRenderer({ curIndex: sliderIndex }) : null}
    </div>
  );
};

 

一些swiper网站地址

https://www.patreon.com/swiperjs

https://swiperjs.com/swiper-api#pagination

https://swiperjs.com/react

https://www.swiper.com.cn/usage/index.html

  

posted @ 2022-06-02 10:28  木杉呀  阅读(55)  评论(0编辑  收藏  举报