本文实例为大家分享了React实现轮播,供大家参考,具体内容如下
思路
1、使用全局的state进行状态管理
2、设置全局下标,对当前的图片下表进行样式划分
3、定时循环人物便利改变全局下标
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" >
< meta http-equiv = "X-UA-Compatible" content = "ie=edge" >
< style >
ul{
width: 100%;
text-align: center;
list-style-type: circle;
}
ul>li{
width: 2%;
float: left;
}
img{
width: 100%;
}
</ style >
< title >轮播事件</ title >
</ head >
< body >
< div id = "root" style = "max-width: 700px;margin: 0 auto;" ></ div >
</ body >
< script src = "./js/react.development.js" ></ script >
< script src = "./js/react-dom.development.js" ></ script >
< script src = "./js/babel.min.js" ></ script >
< script type = "text/babel" >
window.onload=()=>{
class Img extends React.Component{
constructor(props) {
super(props);
this.state={
listImg:[
'./img/banner1.jpg',
'./img/banner2.jpg',
'./img/banner3.jpg',
'./img/banner4.jpg',
'./img/banner5.jpg',
],
index:0
}
}
//计时器执行
indexChange(){
if(this.state.index == this.state.listImg.length-1){
this.setState({
index:0
})
}else{
// this.state.index++;
this.setState({
index:this.state.index+1
})
console.log(this.state.index);
}
}
componentDidMount(){
setInterval(()=>{
this.indexChange();
},2000)
}
render(){
let {listImg,index} = this.state;
let imgList=listImg.map((item,imgIndex)=>{
return < img src={item} key={imgIndex} style={{'display':index == imgIndex ? 'block' : 'none'}} className = 'img' />
})
let liList=listImg.map((item2,imgIndex2)=>{
return < li key={imgIndex2} style={{'listStyleType':index == imgIndex2 ? 'initial' :'circle'}}></ li >
})
return (
< div >
{imgList}
< div >
< ul >
{liList}
</ ul >
</ div >
</ div >
)
}
}
ReactDOM.render(
< Img />,
document.getElementById("root")
)
}
</ script >
</ html >
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_38880700/article/details/94448107