点击切换上一页,下一页

代码用react实现点击切换上一页,下一页

ClickChange.js

import React from 'react';
import './ClickChange.css';
import classnames from 'classnames';

export default class ClickChange extends React.Component {
    constructor(){
        super();
        this.state = {
            currentIndex:1,
            active:'active'
        }
    }
    handleClickPrev = () => {   //上一页
        if(this.state.currentIndex === 1){
            alert('已经是第一页咯!');
        }else{
            const idx = this.state.currentIndex - 1;
            this.setState({currentIndex:idx});
        }
    };
    handleClick = (index) => {  //点击中间数字切换
        this.setState({currentIndex:index});
    };

    handleClickNext = (length) => { //下一页
        if(this.state.currentIndex === length-2){
            alert('已经是最后一页咯!')
        }else{
            const idx = this.state.currentIndex + 1;
            this.setState({currentIndex:idx});
        }
    };

    render() {
        const data = ['上一页','1','2','3','4','5','下一页'];
        let text = data.map((item,index) => {
            const t = index === this.state.currentIndex ;
            const cls = classnames({active:t});
            if(index === 0){
                return <li><span  key={index} className='prev' onClick={this.handleClickPrev.bind(this)}>上一页</span></li>
            }else if(index === data.length - 1){
                return <li><span  key={index} className='next' onClick={this.handleClickNext.bind(this,data.length)}>下一页</span></li>
            }
            return <li key={index} onClick={this.handleClick.bind(this,index)}><span className={cls}>{item}</span></li>
        });
        return (
            <div className='outer'>
                <ul>
                    {text}
                </ul>
            </div>
        );
    }
}

ClickChange.css

*{
    margin:0;
    padding: 0;
}
.outer{
    padding: 10px;
}
ul{
    display: inline-flex;
}
li{
    list-style: none;
    float: left;
}
span{
    border:1px solid #222222;
    padding: 3px 15px;
    margin-left:15px;
    display: inline-flex;
}
span:hover{
    cursor: pointer;
    border:1px solid #b5b5b5;
    color:#b5b5b5;
}
span.active{
    border:1px solid #b5b5b5;
    background: #b5b5b5;
    color:#fff;
}

最后实现效果

 

posted @ 2017-08-10 15:07  讨厌橘子  阅读(974)  评论(0编辑  收藏  举报