swiper插件如何react
安装 Swiper 依赖
在 React 项目中安装 Swiper 的核心库和 React 组件库:
npm install swiper react-id-swiper
或者使用 yarn:
yarn add swiper react-id-swiper
导入 Swiper 组件和样式
在 React 组件中导入 Swiper 和相关样式:
import React from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Navigation, Pagination, Scrollbar, Autoplay } from 'swiper';
import 'swiper/swiper-bundle.min.css';
// 安装 Swiper 模块
SwiperCore.use([Navigation, Pagination, Scrollbar, Autoplay]);
基本 Swiper 使用示例
创建一个简单的轮播组件:
function SimpleSwiper() {
return (
<Swiper
spaceBetween={50}
slidesPerView={3}
navigation
pagination={{ clickable: true }}
scrollbar={{ draggable: true }}
onSlideChange={() => console.log('slide change')}
onSwiper={(swiper) => console.log(swiper)}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
</Swiper>
);
}
配置自动播放
添加自动播放功能:

<Swiper
autoplay={{ delay: 3000 }}
loop={true}
>
{/* 幻灯片内容 */}
</Swiper>
响应式断点配置
针对不同屏幕尺寸配置不同的显示方式:
<Swiper
breakpoints={{
640: {
slidesPerView: 2,
spaceBetween: 20,
},
768: {
slidesPerView: 4,
spaceBetween: 40,
},
1024: {
slidesPerView: 5,
spaceBetween: 50,
},
}}
>
{/* 幻灯片内容 */}
</Swiper>
自定义导航按钮
添加自定义的前进后退按钮:
function CustomNavigationSwiper() {
const swiperRef = React.useRef(null);
return (
<div>
<Swiper
ref={swiperRef}
// 其他配置...
>
{/* 幻灯片内容 */}
</Swiper>
<button onClick={() => swiperRef.current.swiper.slidePrev()}>Previous</button>
<button onClick={() => swiperRef.current.swiper.slideNext()}>Next</button>
</div>
);
}
垂直滑动模式
配置垂直方向的滑动:

<Swiper
direction="vertical"
slidesPerView={1}
mousewheel={true}
>
{/* 幻灯片内容 */}
</Swiper>
懒加载图片
实现图片懒加载功能:
<Swiper
lazy={true}
preloadImages={false}
>
<SwiperSlide>
<img data-src="image1.jpg" className="swiper-lazy" />
<div className="swiper-lazy-preloader"></div>
</SwiperSlide>
{/* 更多幻灯片 */}
</Swiper>
动态添加/删除幻灯片
处理动态内容变化:
function DynamicSwiper({ items }) {
return (
<Swiper>
{items.map((item, index) => (
<SwiperSlide key={index}>
{item.content}
</SwiperSlide>
))}
</Swiper>
);
}
注意事项
确保正确导入 CSS 文件,否则 Swiper 的样式可能无法正常显示。如果遇到样式问题,可以尝试直接导入 Swiper 的 CSS:
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
对于更复杂的配置,参考 Swiper 官方文档获取所有可用参数和事件。






