最近又写新需求,鉴于之前的react-swiper-id太难用了(之前写过,点这里)!所以我准备换成官网上的,结果还是踩了好多坑,一开始用的4.x,加了loop:true后分页器没有了,因为loop机制是复制当前活动swiper的前一个和后一个实现的,所以就导致分页器和真正的index绑定不上了,然后我找了网上好多办法也没改好,索性直接改成6.x版本,但一开始我看的官网的6.x版本也是写的不清不楚的,还是参考了别人写的才成功实现了。
废话不多说,下面直接上代码
import React from 'react';
import SwiperCore, {
Pagination,
Scrollbar,
A11y,
EffectCoverflow,
EffectCube,
Autoplay
} from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/swiper-bundle.css';
import 'swiper/swiper.scss';
import 'swiper/components/pagination/pagination.scss';
import styles from './index.scss';
// 使用哪些插件都需要单独引入
SwiperCore.use([Pagination, Autoplay, EffectCoverflow, EffectCube]);
export default class MySwiper extends React.Component {
let bannerList = [
{ picUrl: ''},
{ picUrl: ''},
{ picUrl: ''},
]
// 初始化
slideConfig = {
tag: 'section',
wrapperTag: 'ul',
// spaceBetween: 50, // 两个slide的间距
slidesPerView: 1,
loop: true,
speed: 2000,
// effect: 'coverflow', // 动画效果
autoplay: {
delay: 2000,
disableOnInteraction: false
},
pagination: { clickable: true },
// scrollbar:{ draggable: true },
onSwiper: (swiper) => console.log(swiper),
onSlideChange: () => console.log('slide change')
};
// 点击事件
clickSwiper(item) {
console.log('执行了swiper点击事件', item);
}
render() {
return (
<div className={styles.treasureWrap}>
<Swiper {...this.slideConfig}>
{bannerList.map((item, index) => (
<SwiperSlide
tag="li"
key={`slide${index + 1}`}
onClick={() => this.clickSwiper(item)}
>
<div key={index}>
<img src={item.picUrl} className={styles.bannerImg} />
</div>
</SwiperSlide>
))}
</Swiper>
</div>
);
}
}
.treasureWrap {
height: 130px;
width: 100%;
background-color: #eaddf0b0;
:global {
.swiper-container {
--swiper-theme-color: #ff6600;
--swiper-pagination-color: #00ff33;
width: 100%;
height: 130px;
background-color: #cfd8e2;
margin-left: auto;
margin-right: auto;
position: relative;
overflow: hidden;
list-style: none;
padding: 0;
z-index: 1;
margin-bottom: 20px;
.swiper-wrapper {
position: relative;
width: 100%;
height: 100%;
z-index: 1;
display: flex;
transition-property: transform;
box-sizing: content-box;
.swiper-slide {
flex-shrink: 0;
width: 100%;
height: 100%;
position: relative;
transition-property: transform;
text-align: center;
}
}
.swiper-pagination {
position: absolute;
bottom: 7px;
left: 0;
width: 100%;
text-align: center;
transition: .3s opacity;
transform: translate3d(0,0,0);
z-index: 10;
.swiper-pagination-bullet {
margin: 0 3.5px;
display: inline-block;
width: 3px;
height: 3px;
background-color: rgba(255, 255, 255, 0.6);
border-radius: 1.5px;
}
.swiper-pagination-bullet-active {
width: 15.5px;
height: 3px;
background-color: rgba(255, 255, 255, 1);
// background: var(--swiper-pagination-color,var(--swiper-theme-color));
border-radius: 1.5px;
}
}
}
}
.bannerImg {
width: 100%;
height: 100%;
object-fit: cover;
object-position: top;
}
}
但是这个引入之后,我们本地使用npm run dev起服务的时候会报一个错误
看提示是swiper自己的错误,我先记录下,回头解决了我再发上来