swiper一直更新是个好事,但使用方法一直在悄悄的变,真得很坑人,直接带过坑吧。
关键在这个引入这里,新版的必须将Autoplay作为模块引入,反正和以前版本有很多不一样了。
javascript
import { Autoplay, EffectFade, Pagination, Navigation } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/react';
// Import Swiper styles
import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css/navigation';
import 'swiper/css/effect-fade';
接下来是组件中引入
javascript
<SwipperWrapper >
<Swiper
spaceBetween={30}
effect={'fade'}
// slidesPerView={3}
centeredSlides={true}
navigation={true}
pagination={{
clickable: true,
}}
modules={[
EffectFade,
Autoplay,
Navigation,
Pagination
]}
autoplay={{
delay: 3000,
disableOnInteraction: false,
}}
loop
>
{slideList?.map(itm => {
return (
<SwiperSlide key={itm.id}>
<img src={`${itm.img}`} alt={itm.title} />
</SwiperSlide>
)
})}
</Swiper>
</SwipperWrapper>
再根据demo设置自定义样式,这个不是必须的了,只是图片等更合理的一些设置而已,可以自己定义:
javascript
export const SwipperWrapper = styled.div`
margin-top:3rem;
.swiper {
width: 100%;
height: 100%;
}
.swiper-slide {
background-position: center;
background-size: cover;
}
.swiper-slide img {
display: block;
width: 100%;
}
`;
其他说明,新版本的swiper在react中基本上都是以模块或组件引入了,如果有些效果不起作用,说明你得使用方法和对应版本可能不一样,重新根据官网版本安装指定版本或自己找对应版本的demo再进行设置。
下面是自己需要用到的样式,需要那个就必须应用对应的样式,注意这个与低版本的路径也不一样了。
Styles
Swiper package contains different sets of CSS, Less and SCSS styles:
swiper/css
- only core Swiper stylesswiper/css/bundle
- all Swiper styles including all modules styles (like Navigation, Pagination, etc.)
Modules styles (not required if you already imported bundle styles):
swiper/css/a11y
- styles required for A11y moduleswiper/css/autoplay
- styles required for Autoplay moduleswiper/css/controller
- styles required for Controller moduleswiper/css/effect-cards
- styles required for Cards Effect moduleswiper/css/effect-coverflow
- styles required for Coverflow Effect moduleswiper/css/effect-creative
- styles required for Creative Effect moduleswiper/css/effect-cube
- styles required for Cube Effect moduleswiper/css/effect-fade
- styles required for Fade Effect moduleswiper/css/effect-flip
- styles required for Flip Effect moduleswiper/css/free-mode
- styles required for Free Mode moduleswiper/css/grid
- styles required for Grid moduleswiper/css/hash-navigation
- styles required for Hash Navigation moduleswiper/css/history
- styles required for History moduleswiper/css/keyboard
- styles required for Keyboard moduleswiper/css/manipulation
- styles required for Manipulation moduleswiper/css/mousewheel
- styles required for Mousewheel moduleswiper/css/navigation
- styles required for Navigation moduleswiper/css/pagination
- styles required for Pagination moduleswiper/css/parallax
- styles required for Parallax moduleswiper/css/scrollbar
- styles required for Scrollbar moduleswiper/css/thumbs
- styles required for Thumbs moduleswiper/css/virtual
- styles required for Virtual moduleswiper/css/zoom
- styles required for Zoom module