2025年4月8日 星期二 乙巳(蛇)年 正月初九 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

基于React使用swiperjs实现竖向滚动自动轮播

时间:05-22来源:作者:点击数:58

很多文章,都只提供了js部分,包括官方的文档也只有js部分,如果css设置不正确,会导致轮播图不自动播放。

使用的swiper版本:v11.0.3

文档

实现效果

在这里插入图片描述

使用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">
  • <Swiper
  • modules={[Autoplay]}
  • direction="vertical"
  • loop={true}
  • slidesPerView={1}
  • autoplay={{
  • delay: 3000, // ms
  • }}
  • >
  • {list.map((item, index) => {
  • return (
  • <SwiperSlide>
  • <div
  • className="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;
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门