(demo)在react18中使用swiper@8.0.1实现轮播图

489 阅读1分钟

效果如下

轮播书籍.png

安装依赖

移除之前版本的swiper yarn remove swiper

安装8.0.1版本 yarn add swiper@8.0.1

注意

由于react18使用的是strictMode严格模式,会导致在组件加载时,无法获取到swiper的类,所以在使用swiper@6.8.4版本时会报错:

TypeError: Cannot read properties of undefined (reading 'wrapperClass') React18中使用swiper@6.8.4,出现了报错

引入组件与样式

import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay, Navigation } from "swiper";

import "swiper/css";

配置swiper

直接上代码

import React from "react";
import { useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
// 从swiper中引入且需要加入modules数组
import { Autoplay, Navigation } from "swiper";
import { LeftOutlined, RightOutlined } from "@ant-design/icons";

import defaultImg from "@/assets/home/CollectionUpdate/default.png";
import "./index.scss";
import "swiper/css";

const Update = (props) => {
  const [collectionsList, setCollectionsList] = useState([
    {
      imgSrc: defaultImg,
      title: "别名格蕾丝",
      author: "朱迪斯·巴特勒",
      intro: "精神病院的女犯不比英国女皇疯",
      status: "1",
      time: "刚刚",
      bookStatus: "update",
    },
    ...
  ]);

  return (
    <div className="booklist-con">
      <Swiper
        // 导入 Autoplay  Navigation 模块
        modules={[Autoplay, Navigation]}
        // 自动播放
        // modules上加了后同时要设置为true才生效
        autoplay
        // 设置item之间的距离
        spaceBetween={24}
        // 设置显示的数量页面显示超过3个才能滑动
        slidesPerView={3}
        // 配置左右导航按钮
        navigation={{ prevEl: ".prev", nextEl: ".next" }}
      >
        {collectionsList.map((item, index) => {
          return (
            <SwiperSlide key={index}>
              <div className="book-con">
                {/* 每个item的结构 */}
              </div>
            </SwiperSlide>
          );
        })}
      </Swiper>
      
      <div className="prev flexBoxCenter">
       {/* 这里自定义前进/后退的按钮,定位在轮播图两边 */}
        <LeftOutlined />
      </div>
      <div className="next flexBoxCenter">
        <RightOutlined />
      </div>
    </div>
  );
};

export default Update;