3.分頁處理-React部分
和一般的ajax一樣,只是把結果塞在自制的Pagenator Component.
{(recipes.pagination) ? (
<Paginator previousClassName={cx('pege_arr-l', {'arr_no': !recipes.pagination.isFirstPage})}
pageClassName="btm_in"
nextClassName={cx('pege_arr-r', {'arr_no': !recipes.pagination.isLastPage})}
items={recipes.pagination.items}
currentpage={recipes.pagination.currentpage}
clickCallback={::this.onClickCallback}
total={recipes.pagination.total}
/>) : null}
previousClassName,pageClassName,nextClassName方便定義外觀
items是頁數的List(包含"...")
currentpage是目前的頁數
total是總筆數
clickCallback是點下去之後發生的事情
目前我讓它傳回url在內部變成一個page
但其實可以配合react-router來做換頁動作。
onClickCallback(item) {
let result = null;
if (typeof this.props.url !== 'undefined') {
result = (this.props.url.params) ?
((this.props.url.params.page) ?
this.props.path.replace(/page=\d+/i, 'page=' + item)
: this.props.path + '&page=' + item)
: this.props.path + '?page=' + item;
}
return result;
}
Pagenator Component內部長這樣
import React, { Component, PropTypes } from 'react';
import _ from 'lodash';
export default class Paginator extends Component {
static propTypes = {
previousClassName: PropTypes.string,
nextClassName: PropTypes.string,
pageClassName: PropTypes.string,
clickCallback: PropTypes.func,
items: PropTypes.array,
currentpage: PropTypes.string,
total: PropTypes.number
}
render() {
return (
<div className="PageBox">
<p> <a className={this.props.previousClassName} href={this.props.clickCallback(this.props.currentpage - 1)} />{/*在沒有前一頁時會增加arr_no這class屬性,表示無法點選*/}
{_.map(this.props.items, (item, index)=> {
let pageClassName = '';
if (this.props.currentpage === item) {
pageClassName += this.props.pageClassName;
}
return (index > this.props.items.length - 4 || index < 3) && (<a href={this.props.clickCallback(item)} key={item} className={pageClassName}>{item}</a>);
})}
<span>總共</span>{this.props.total}<span>筆</span>
<a className={this.props.nextClassName} href={this.props.clickCallback(this.props.currentpage + 1)} />{/*相同的在沒有下一頁時會增加arr_no這屬性,表示無法點選*/}
</p>
</div>
);
}
}
蠻單純的,之後再依照自已的需要去改動。
其實也有套件可以用 https://github.com/AdeleD/react-paginate 不過套件還要看它的說明就是,依個人需求決定如何處理吧。
處理完大概會長這樣