一个简单的demo,react写轮播组件
1、SwipePlayer.js
import React from 'react';
import './demo.css'
class SwipePlayer extends React.Component {
constructor(props) {
super(props)
this.state = {
index: 0 // 当前轮播第几个图片
}
}
// 点击播放下一张
_nextImg () {
var { index } = this.state;
if (index === this.props.images.length - 1) {
index = 0;
} else {
index++
}
this.setState({
index: index
})
}
// 点击播放上一张
_prevImg () {
var { index } = this.state;
if (index === 0) {
index = this.props.images.length - 1
} else {
index--
}
this.setState({
index: index
})
}
// 当鼠标停留在图片上时
mouseHoverImg () {
clearInterval(this.timerId)
}
mouseLeaveImg () {
this.play()
}
play () {
this.timerId = setInterval(() => {
this._nextImg()
}, 3000)
}
componentDidMount () {
this.play()
}
componentWillUnmount () {
clearInterval(this.timerId)
}
render () {
var { index } = this.state;
return (
<div className="wrap">
<ul className="list">
{
this.props.images.map((item, i) => (
<li className={`item ${i === index ? 'active' : ''}`} key={i}
onMouseOver={() => this.mouseHoverImg()}
onMouseLeave={() => this.mouseLeaveImg()}>
<img src={item} alt="" />
</li>
))
}
</ul>
<button className="btn left" onClick={() => this._prevImg()} onMouseOver={() => this.mouseHoverImg()}
onMouseLeave={() => this.mouseLeaveImg()}><</button>
<button className="btn rigth" onClick={() => this._nextImg()} onMouseOver={() => this.mouseHoverImg()}
onMouseLeave={() => this.mouseLeaveImg()}>></button>
</div>
)
}
}
export default SwipePlayer;
2、demo.css
ul{
list-style: none;
margin: 0px;
padding: 0px;
}
.wrap{
position: relative;
width: 1000px;
height: 600px;
}
.list{
position: relative;
width: 100%;
height: 100%;
}
.list .item{
position: absolute;
top: 0px;
width: 100%;
height: 100%;
overflow: hidden;
z-index: 0;
}
.list .item.active{
z-index: 10;
}
.list .item img{
width: 100%;
}
.wrap .btn{
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 60px;
height: 100px;
background: rgba(0,0,0,.5);
color: #fff;
border: none;
cursor: pointer;
transition: all .3s;
z-index: 20;
}
.wrap .btn:hover{
background: rgba(0,0,0,.8);
}
.wrap .btn.left{
left: 0px;
}
.wrap .btn.rigth{
right: 0px;
}
3、父组件
import React from 'react';
import image_1 from './images/java.jpg'
import image_2 from './images/sakula.jpg'
import image_3 from './images/timg.jpg'
import SwipePlayer from './SwipePlayer'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
images: [image_1, image_2, image_3]
}
}
render () {
return (
<div>
<SwipePlayer images={this.state.images}></SwipePlayer>
</div>
)
}
}
export default App;