react如何使用swiper
安装 Swiper 依赖
在 React 项目中安装 Swiper 的核心库和 React 组件库:
npm install swiper react-id-swiper
# 或使用 yarn
yarn add swiper react-id-swiper
引入 Swiper 组件和样式
在需要使用 Swiper 的组件中引入必要的模块和 CSS:
import React from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/swiper-bundle.min.css';
// 按需引入模块(如导航、分页等)
import { Navigation, Pagination } from 'swiper';
基础 Swiper 配置
创建一个简单的轮播组件,配置基础参数:
function MySwiper() {
return (
<Swiper
modules={[Navigation, Pagination]}
spaceBetween={50}
slidesPerView={3}
navigation
pagination={{ clickable: true }}
onSlideChange={() => console.log('slide change')}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
</Swiper>
);
}
自定义样式和效果
通过 CSS 覆盖或 Swiper 参数调整视觉效果:
<Swiper
autoplay={{ delay: 3000 }}
loop={true}
effect={'fade'}
style={{ height: '300px' }}
>
{/* 幻灯片内容 */}
</Swiper>
响应式配置
使用 breakpoints 参数实现不同屏幕尺寸下的适配:
<Swiper
breakpoints={{
640: { slidesPerView: 2 },
1024: { slidesPerView: 4 }
}}
>
{/* 幻灯片内容 */}
</Swiper>
注意事项
确保 Swiper 的 CSS 文件正确导入,避免样式冲突。对于复杂场景(如动态数据加载),需在数据更新后调用 swiper.update() 方法。服务器端渲染(SSR)需额外处理 Swiper 的窗口对象依赖问题。







