跳到主要内容

vant-swipe轮播实例

https://react-vant.3lang.dev/components/swiper#swipe-props

@site/src/components目录创建vant目录。

安装react-vant

yarn add react-vant

样式

style.scss

:root {
--rv-swipe-indicator-active-opacity: 1; /*小圆点有鼠标时的透明度*/
--rv-swipe-indicator-inactive-opacity: 0.4; /*小圆点没有鼠标时的透明度*/
--rv-swipe-indicator-active-background-color: rgb(255, 0, 0); /*小圆点选中颜色,表示当前图片*/
--rv-swipe-indicator-inactive-background-color: rgb(0, 0, 0); /*小圆点选前颜色*/
--card-height: 300px; /*显示区块高度*/
--card-widht: 100vw; /*显示区块宽度*/
--rv-swipe-background-color: rgb(240, 240, 240); /*显示区块背景色*/
}

.img {
width: auto;
height: var(--card-height);
/*border-style: dotted;*/
pointer-events: auto;
box-shadow: 0 2px 10px 10px rgba(110, 108, 108, 0.2);
background-color: rgb(238, 238, 238);
}

.img:hover {
box-shadow: 0 5px 13px 13px rgba(110, 108, 108, 0.2);
background-color: rgb(216, 216, 218);
}

.demo-swiper {
.rv-swiper {
&__slide {
.rv-swiper-item {
font-size: 20px;
text-align: center;
display: flex;
align-items: center;
padding: 40px;
justify-content: center;
}

/* nth-child(odd) 与 nth-child(even) 是用于配置图片交替出现时显示风格*/
&:nth-child(odd) {
.rv-swiper-item {
background-color: var(--rv-swipe-background-color);
}
}

&:nth-child(even) {
.rv-swiper-item {
/*background-color: lighten(#c2c2d1, 8%);*/
background-color: var(--rv-swipe-background-color);
}
}
}
}
}

实现代码

index.js
import React from 'react'
import { Swiper, Image } from 'react-vant'
import './style.scss'

const jsonData = [
{
imgAdd:'/img/rs/a01.png',
imgUrl:'https://www.baidu.com',
imgDescription: 'test1',
imgTitle: 'test1',
},
{
imgAdd:'/img/rs/a02.png',
imgUrl:'#',
imgDescription: 'test2',
imgTitle: 'test2',
},
{
imgAdd:'/img/rs/a03.png',
imgUrl:'#',
imgDescription: 'test3',
imgTitle: 'test3',
},
{
imgAdd:'/img/rs/wx.png',
imgUrl:'#',
imgDescription: 'wx',
imgTitle: 'wx',
},
{
imgAdd:'/img/rs/logo.png',
imgUrl:'#',
imgDescription: 'logo',
imgTitle: 'logo',
},
{
imgAdd:'/img/rs/os-w.gif',
imgUrl:'#',
imgDescription: 'os-w',
imgTitle: 'os-w',
},
]


const items = jsonData.map((obj, index) => (
<Swiper.Item key={index}>
<div>
<div><h2>{obj.imgTitle}</h2></div>
<div><a href={obj.imgUrl} target='_blank' ><img className='img' src={obj.imgAdd} title={obj.imgTitle} /></a></div>
<div>{obj.imgDescription}</div>
</div>
</Swiper.Item>
))

function vant() {
return (
<div className="demo-swiper">
<Swiper
autoplay={3000} //是否自动轮播
touchable={true} //是否可以通过手势滑动
>
{items}
</Swiper>
</div>
)
}

export default vant;

效果