react 轮播组件封装

轮播组件

1 dom加载后自动轮播

2 图片循环轮播

2 手动轮播时停止自动轮播,手动轮播结束2s后启动自动轮播

import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';


class Ha extends React.Component {
    constructor(props) {
        super(props);
        // 设置 initial state
        this.state = {
            moves:0,
            imgs:['./1.jpg','./2.jpg','./3.jpg','./4.jpg','./5.jpg'],
            constLeft:200,
            timer:null,//定时器轮播
            timer2:null,//延迟器 延迟两秒启动定时器
        
        };
        
      this.option = this.option.bind(this);
    }
    componentDidMount() {
        const Timer1 = setInterval(()=>{
            this.option(1)
        }, 1000);
        this.setState({timer:Timer1});
      }
    timeOut = ()=>{//手动点击后启动延迟器
   //这样写,就不用再手动绑定this了
        const Timer2 = setTimeout(()=>{//手动点击后延迟两秒启动定时去
            const Timer3 = setInterval(()=>{//定时器定时轮播
                this.option(1);
            },1000);
            this.setState({timer:Timer3});
        },2000)
        this.setState({timer2:Timer2});
    }
    option(flag,option1){
        const {timer,moves,constLeft,timer2}=this.state;
        option1&&clearInterval(timer)//手动点击时清除定时器
        timer2&&clearTimeout(timer2);//手动点击时当延迟器存在时清除
        if(flag>0){//右边
            if(moves<=0 &&moves>-800){
                this.setState({moves:moves-constLeft})    
            }else{
                this.setState({moves:0})
            }
          }else{//左边
            if(moves<0){
                this.setState({moves:moves+constLeft})
            }else{
                this.setState({moves:-800});
            }
            
          }
          option1&&this.timeOut();//手动点击后启动延迟器
    }
    showList() {
       return (
           <div className='box-box'>
                <span className='icon1 ' onClick={()=>this.option(-1,1)}>left</span> 
               
            <div className='box'>
                <ul className='list' style={{left:this.state.moves+'px'}}>
                    {   
                        this.state.imgs.map((item, index) => {
                            return (
                            <li key={index} >
                                <img src={item}/>
                            </li>
                            )
                            
                        })
                    }
                </ul>
                 </div>
                 <span className='icon1 icon2' onClick={()=>this.option(1,1)}>right</span> 
       
        </div>
        )
      } 
    render() {
        return (
            <div>
                {this.showList()}
            </div>
        );
    }
}
export default Ha;
posted @ 2021-03-11 17:30  青橙娃娃  阅读(181)  评论(0编辑  收藏  举报