react如何引入swiper
安装 Swiper 依赖
在 React 项目中安装 Swiper 的核心库和样式文件,可以通过 npm 或 yarn 完成:
npm install swiper
# 或
yarn add swiper
导入 Swiper 模块
在需要使用 Swiper 的组件中,导入 Swiper 的核心模块、样式以及 React 专用组件:
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';
基础使用示例
创建一个简单的轮播组件,配置默认参数(如循环、分页等):
function MySwiper() {
return (
<Swiper
spaceBetween={50}
slidesPerView={3}
loop={true}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
</Swiper>
);
}
添加导航与分页
如需添加导航按钮或分页器,需导入对应模块并配置:
import { Navigation, Pagination } from 'swiper/modules';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
function MySwiper() {
return (
<Swiper
modules={[Navigation, Pagination]}
navigation
pagination={{ clickable: true }}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
</Swiper>
);
}
自定义样式
通过 CSS 覆盖默认样式或调整布局:
.swiper-slide {
background: #eee;
display: flex;
justify-content: center;
align-items: center;
}
响应式配置
通过 breakpoints 参数实现不同屏幕尺寸下的适配:

<Swiper
breakpoints={{
640: { slidesPerView: 2 },
1024: { slidesPerView: 3 },
}}
>
{/* Slides */}
</Swiper>






