React 轮播
需要的资源:几张图片 我放的是在当前组件目录下的 images 目录下
依赖的框架:UI框架 ant-desigin (因为使用的React就选择了 ant-desigin,如果大家使用的是其他可以选择对应的;例如 Vue的话可以选择 Element,原生语言可以借助bootstrap这些。当然也可以不借助任何帮助,自己手写样式。)
闲聊到此为止了哈,下面开始主题
![文件目录结构](https://img-blog.csdnimg.cn/20201201115332408.png)
正文代码
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 Lunbo 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 Lunbo;
滚动代码
import React from 'react';
import './swipper.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;
样式代码
ul{
list-style: none;
margin: 0px;
padding: 0px;
}
.wrap{
position: relative;
width: 1000px;
height: 300px;
}
.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;
}
不足之处,多多指教