Posted in Javascript onAugust 25, 2020
本文实例为大家分享了React实现轮播,供大家参考,具体内容如下
思路
1、使用全局的state进行状态管理
2、设置全局下标,对当前的图片下表进行样式划分
3、定时循环人物便利改变全局下标
<!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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。
React实现轮播效果
- Author -
越来越好。声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@