很多文章,都只提供了js部分,包括官方的文档也只有js部分,如果css设置不正确,会导致轮播图不自动播放。
使用的swiper版本:v11.0.3
文档
- https://swiperjs.com/get-started
- https://swiperjs.com/react
实现效果
使用vite创建react应用
pnpm create vite react-app --template react
完整依赖 package.json
{"dependencies": {"react": "^18.2.0","react-dom": "^18.2.0","swiper": "^11.0.3"},"devDependencies": {"@types/react": "^18.2.15","@types/react-dom": "^18.2.7","@vitejs/plugin-react": "^4.0.3","eslint": "^8.45.0","eslint-plugin-react": "^7.32.2","eslint-plugin-react-hooks": "^4.6.0","eslint-plugin-react-refresh": "^0.4.3","vite": "^4.4.5"}
}
App.js
// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";// import Swiper core and required modules
import { Autoplay } from "swiper/modules";// import Swiper styles
import "swiper/css";
import "swiper/css/autoplay";import "./App.css";// 获取一个随机颜色值
function randomColor() {let r = Math.floor(Math.random() * 255);let g = Math.floor(Math.random() * 255);let b = Math.floor(Math.random() * 255);return `rgb(${r},${g},${b})`;
}// 轮播数据
const list = [{backgroundColor: randomColor(),},{backgroundColor: randomColor(),},{backgroundColor: randomColor(),},{backgroundColor: randomColor(),},
];function App() {return (<div className="swiper__wrap"><Swipermodules={[Autoplay]}direction="vertical"loop={true}slidesPerView={1}autoplay={{delay: 3000, // ms}}>{list.map((item, index) => {return (<SwiperSlide><divclassName="swiper__slide"style={{ backgroundColor: item.backgroundColor }}>{index + 1}</div></SwiperSlide>);})}</Swiper></div>);
}export default App;
App.css
.swiper__wrap {margin: 0 auto;margin-top: 200px;
}.swiper {height: 200px;width: 300px;
}.swiper__slide {line-height: 200px;background-color: pink;color: #fff;text-align: center;
}
轮播的关键
需要设置swiper容器的尺寸
.swiper {height: 200px;width: 300px;
}