1、安装
cnpm install --save react-swipeable-views
2、引入
import SwipeableViews from 'react-swipeable-views';
import { autoPlay } from 'react-swipeable-views-utils';
const AutoPlaySwipeableViews = autoPlay(SwipeableViews);
3、使用
<AutoPlaySwipeableViews style={{height:'200px'}}
interval={3000}
onChangeIndex={ this.handleChangeIndex } 轮播改变回调,第一个参数是索引
>
<div>slide n°1</div>
<div>slide n°1</div>
<div>slide n°1</div>
</AutoPlaySwipeableViews>
4、样式按照正常css自定义
5、分页器需要自己写组件
代码示例:
轮播
import React,{Component} from 'react';
import SwipeableViews from 'react-swipeable-views';
import { autoPlay } from 'react-swipeable-views-utils';
import Pagination from './pagination/index'
const AutoPlaySwipeableViews = autoPlay(SwipeableViews);
const styles = {
slide: {
minHeight: 100,
color: '#fff',
},
slide1: {
height:'200px',
width:'100%'
},
slide2: {
height:'200px'
},
slide3: {
height:'200px'
},
};
class App extends Component{
constructor()
{
super();
this.state={
currentIndex:0
}
}
handleChangeIndex = index => {
this.setState({
currentIndex:index
})
}
render()
{
const banners=this.props.banners;
return(
<div className='swiper' style={{height:'200px',position:'relative'}}>
<AutoPlaySwipeableViews style={{height:'200px'}}
interval={3000}
onChangeIndex={ this.handleChangeIndex }
>
{
banners.map((item,index)=>{
return (
<div key={index} className="swiper-view" style={Object.assign({}, styles.slide, styles.slide1)}>
<img src={item} style={{height:'200px',width:'100%'}} alt="" />
</div>
)
})
}
</AutoPlaySwipeableViews>
<Pagination dots={banners.length} index={this.state.currentIndex} style={{height:'200px',position:'absolute'}} />
</div>
)
}
}
export default App
分页器:
import React from "react"
import "./style.less"
export default class Pagination extends React.Component {
render() {
const dots = this.props.dots;
const dotsArr = new Array(dots).fill(1);
const currentIndex = this.props.index;
return (
<div className="swiper-pagination">
<ul>
{
dotsArr.map((element,index) => {
return <li className={ currentIndex === index ? 'selected' : ''} key={index}></li>
})
}
</ul>
</div>
)
}
}
分页器样式:
.swiper-pagination{
position: absolute;
bottom: 10px;
right: 10px;
ul {
width: 100%;
height: auto;
text-align: center;
}
li {
list-style: none;
display: inline-block;
height: 10px;
width: 10px;
border-radius: 50%;
background-color: #ccc;
margin: 0 3px;
}
li.selected {
background-color: rgb(233, 32, 61);
}
}
效果图: