前言
分頁其實很容易實現(xiàn)矗烛,我自己寫了一個簡單的分頁組件躁锡,可以實現(xiàn)上下翻頁则涯,輸入頁碼跳轉(zhuǎn)到指定頁,刷新頁面后不會回到第一頁(hash值記錄當(dāng)前頁碼)杨刨。效果如下:
功能分析
把這個組件拆開看晤柄,其實就是三個功能:
- 翻頁(基本功能)
- 跳轉(zhuǎn)到指定頁
- 記錄頁碼(利用hash)
父組件向分頁組件需要傳遞兩個值:數(shù)據(jù)總數(shù),一頁顯示幾條數(shù)據(jù)妖胀。
<Pagination
total={this.state.total}
pageSize = {this.pageSize}
/>
翻頁功能實現(xiàn)
分頁組件:
constructor(props) {
super(props);
this.state = {
currentPageNum: props.currentPageNum, //當(dāng)前頁碼
}
}
render() {
let pageTotal = Math.ceil(this.props.total / this.props.pageSize); //頁碼總數(shù)
return (
<section>
<a href="javascript:void(0)">上一頁 </a>
<div>
<input type="text" value={this.state.currentPageNum} />
<span>/{pageTotal}</span>
</div>
<a href="javascript:void(0)">下一頁 </a>
</section>
)
}
}
當(dāng)前頁碼currentPageNum
是從父組件傳遞過來的值芥颈,一般情況下不需要傳這個值,我之前是從父組件更改它赚抡,后來修改了代碼爬坑,就在組件里更新它,不過父組件也可以傳當(dāng)前頁碼過來涂臣。
到這里就完成了基本的分頁組件展示了盾计,接下來開始實現(xiàn)上一頁和下一頁功能。
給上一頁和下一頁綁定事件:
<a href="javascript:void(0)" onClick={() => this.goToPage(this.state.currentPageNum-1)}>上一頁 </a>
<a href="javascript:void(0)" onClick={() => this.goToPage(this.state.currentPageNum+1)}>下一頁 </a>
goToPage()方法:
//翻頁
goToPage(num) {
this.setState({currentPageNum: num});
this.props.goToPage(num);
}
這里this.props.goToPage()是子組件調(diào)用父組件傳過來的方法赁遗。點擊翻頁的時候署辉,子組件也需要向父組件傳參,并調(diào)用該方法吼和,通過回調(diào)函數(shù)就實現(xiàn)了子組件向父組件傳值涨薪。
父組件要傳遞這個函數(shù):
<Pagination
total={this.state.total}
pageSize = {this.pageSize}
currentPageNum = {this.state.currentPageNum}
goToPage = {(pageNum) => this.goToPage(pageNum)}
/>
這里父組件就可以獲取到翻頁子組件傳過來的頁碼,然后根據(jù)這個頁碼發(fā)起網(wǎng)絡(luò)請求炫乓,這里怎么寫和后臺有關(guān),比如我們的后臺是有分頁的献丑,我要請求第幾頁末捣,請求多少條數(shù)據(jù)傳遞給后臺就可以,可能有的后臺是返回了全部數(shù)據(jù)创橄,然后前端去處理分頁箩做,那就不是發(fā)起網(wǎng)絡(luò)請求,而是將當(dāng)前顯示的數(shù)據(jù)index往后移 當(dāng)前頁碼currentPageNum * 一頁顯示數(shù)據(jù)條數(shù)pageSize
這么多位置妥畏,以實現(xiàn)翻頁效果邦邦。
父組件的翻頁事件:
//翻頁
goToPage(pageNum) {
this.requestNewsData(pageNum); //網(wǎng)絡(luò)請求的方法
}
以上短短幾行代碼就實現(xiàn)了翻頁,不過還不夠完善燃辖,比如我并沒有對上一頁和下一頁按鈕做限制,即如果當(dāng)前是第一頁和最后一頁就不能再觸發(fā)goToPage()方法了网棍,所以我應(yīng)該在goToPage()里面去判斷當(dāng)前頁碼是否是第一頁或者最后一頁黔龟,這里我采用了另一種方式。
注意看頁面按鈕是有兩種狀態(tài),當(dāng)不可點擊時箭頭是灰色的氏身,大部分翻頁都有這個效果巍棱,我覺得最好的方式是使用兩種標(biāo)簽:可點擊狀態(tài)的<a>標(biāo)簽和不可點擊的<span>標(biāo)簽,使用三目運算符做判斷蛋欣,這樣就保證了currentPageNum-1或者+1都不會越界航徙。
以下是對上一頁按鈕做的處理:
//nextBtnDisabled是不可點擊狀態(tài)的圖標(biāo),nextBtn是可點擊狀態(tài)的圖標(biāo)
{this.state.currentPageNum === 1 ?
<span>
<img src={nextBtnDisabled} alt=""/>
</span>
:
<a href="javascript:void(0)" onClick={() => this.goToPage(this.state.currentPageNum-1)}>
<img src={nextBtn} alt="" />
</a>
}
下一頁按鈕類似陷虎,只需將this.props.currentPageNum === 1
改為this.props.currentPageNum === pageTotal
,我覺得在這里做判斷是最簡單的做法到踏,這樣無需考慮頁碼越界的問題,而且視覺上也讓用戶體驗更好泻红。
輸入頁碼跳轉(zhuǎn)到指定頁功能實現(xiàn)
給input框綁定事件:
<input
type="text"
value={this.state.currentPageNum}
onChange={this.changePageNumber.bind(this)}
onKeyUp={(event) => this.handleKeyUp(event, pageTotal)}
/>
onChange事件當(dāng)輸入框值發(fā)生變化時被觸發(fā)夭禽,輸入框的值即當(dāng)前頁碼
//頁碼輸入框
changePageNumber(event) {
this.setState({
currentPageNum: event.target.value
});
}
onKeyUp事件是鍵盤按下事件,我是在按下回車鍵的時候觸發(fā)更新谊路,另外讹躯,也需要做判斷,判斷是否是合法的頁碼:
//鍵盤按下事件,pageTotal是頁碼數(shù)
handleKeyUp(e, pageTotal) {
let value = e.target.value;
let event = e || window.event;
let code = event.keyCode || event.which || event.charCode;
if (code === 13) { //回車鍵
if (isNaN(value)) { //isNaN() 不是一個數(shù)字返回true
alert('請輸入數(shù)字缠劝!')
} else if(value > pageTotal || value === null || value.trim() === '') { //使用trim()去掉空格潮梯,全為空格的字符串不為''也不為null
alert('請輸入合法的頁碼')
} else {
this.goToPage(parseInt(value, 10)) //輸入了合法頁碼,調(diào)用跳轉(zhuǎn)頁面方法惨恭。
}
}
}
分頁錨點功能實現(xiàn)(使用react-router-dom)
一般有分頁的地方都會有錨點秉馏,記錄當(dāng)前頁碼,當(dāng)瀏覽器刷新或者回退時可以定位到當(dāng)前頁碼脱羡,因為我的路由用的react-router-dom,所以頁面跳轉(zhuǎn)用Link萝究,這里將a標(biāo)簽替換成Link標(biāo)簽:
import { Link } from 'react-router-dom';
{/*下一頁按鈕只是將this.state.currentPageNum-1改為this.state.currentPageNum+1*/}
<Link
to={{
pathname: '/blog',
hash: `#${this.state.currentPageNum-1}`
}}
onClick={() => this.goToPage(this.state.currentPageNum-1)}
>
<img src={preBtn} alt="" />
</Link>
//pathname的值是博客頁的路由
hash: #${this.state.currentPageNum-1}
就是將頁碼設(shè)置為hash值,會顯示在url地址欄中锉罐,比如:www.baidu.com#2
這種形式帆竹。這樣就實現(xiàn)了將頁碼作為錨點的功能,不過要實現(xiàn)刷新時依然在當(dāng)前頁碼脓规,還需要在componentDidMount
里面手動解析url將頁碼取出來然后再調(diào)用goToPage()
方法:
componentDidMount() {
this.handleAnchor() //頁面刷新時回到刷新前的page
}
handleAnchor() {
let index = window.location.hash.slice(1) || 1; //獲取hash值
this.goToPage(parseInt(index, 10));
}
最后還有輸入頁碼當(dāng)頁碼合法時跳轉(zhuǎn)到指定頁也需要添加hash值:
window.location.hash = `#${value}`;
代碼
分頁組件:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import './style.css';
import nextBtn from './images/nextBtn.png';
import preBtnDisabled from './images/preBtn-disabled.png';
export default class Pagination extends Component {
constructor(props) {
super(props);
this.state = {
currentPageNum: 1,
}
}
componentDidMount() {
this.handleAnchor() //頁面刷新時回到刷新前的page
}
handleAnchor() {
let index = window.location.hash.slice(1) || 1;
this.goToPage(parseInt(index, 10));
}
//翻頁
goToPage(num) {
this.setState({currentPageNum: num});
this.props.goToPage(num);
}
//頁碼輸入框
changePageNumber(event) {
this.setState({
currentPageNum: event.target.value
});
}
//鍵盤按下事件
handleKeyUp(e, pageTotal) {
let value = e.target.value;
let event = e || window.event;
let code = event.keyCode || event.which || event.charCode;
if (code === 13) { //回車鍵
if (isNaN(value)) { //isNaN() 不是一個數(shù)字返回true
alert('請輸入數(shù)字栽连!')
} else if(value > pageTotal || value === null || value.trim() === '') { //使用trim()去掉空格,全為空格的字符串不為''也不為null
alert('請輸入合法的頁碼')
} else {
window.location.hash = `#${value}`;
this.goToPage(parseInt(value, 10)) //這里一定要將value類型轉(zhuǎn)換為數(shù)字侨舆,用戶手動輸入頁碼很有可能是string秒紧。而最好在這里轉(zhuǎn)換是因為已經(jīng)過濾了不是數(shù)字和空的值,不會出現(xiàn)NaN的情況
}
}
}
render() {
let pageTotal = Math.ceil(this.props.total / this.props.pageSize); //頁碼總數(shù)
return (
<section className="pagination">
{this.state.currentPageNum === 1 ?
<span className="pagination-button">
<img src={preBtnDisabled} alt=""/>
</span>
:
<Link
to={{
pathname: '/blog',
hash: `#${this.state.currentPageNum-1}`
}}
className="pagination-button pre-button"
onClick={() => this.goToPage(this.state.currentPageNum-1)}
>
<img src={nextBtn} alt="" style={{transform: 'rotate(180deg)'}}/>
</Link>
}
<div className="pagination-pageNumber">
<p>
<input
type="text"
value={this.state.currentPageNum}
onChange={this.changePageNumber.bind(this)}
onKeyUp={(event) => this.handleKeyUp(event, pageTotal)}
/>
<span>/ {pageTotal}</span>
</p>
</div>
{this.state.currentPageNum === pageTotal ?
<span className="pagination-button">
<img src={preBtnDisabled} alt="" style={{transform: 'rotate(180deg)'}}/>
</span>
:
<Link
to={{
pathname: '/blog',
hash: `#${this.state.currentPageNum+1}`
}}
className="pagination-button next-button"
onClick={() => this.goToPage(this.state.currentPageNum+1)}
>
<img src={nextBtn} alt="" />
</Link>
}
</section>
)
}
}
Pagination.defaultProps = {
pageSize: 5,
currentPageNum: 1,
};
Pagination.propTypes = {
total: PropTypes.number.isRequired, //數(shù)據(jù)總數(shù)
pageSize: PropTypes.number, //一頁顯示幾條數(shù)據(jù)
currentPageNum: PropTypes.number, //當(dāng)前頁碼
};
調(diào)用方法:
import React, { Component } from 'react';
import Pagination from '../components/pagination';
class Test extends Component {
constructor(props) {
super(props);
this.state = {
total: 0, //數(shù)據(jù)總數(shù)
data: [],
};
this.pageSize = 10; //一頁顯示的數(shù)據(jù)條數(shù)
}
//獲取數(shù)據(jù)
requestData() {
fetch('http://localhost:3100/test.json').then(response => response.json())
.then(res => {
this.setState({
total: res.total,
data: res.data
})
})
.catch(err => console.log('err', err))
}
//翻頁
goToPage(pageNum) {
this.requestData();
}
render() {
let blogItem = this.state.data && this.state.data.map((item, index) => {
return (
<section key={index}>
<p>{item.categoryName}</p>
<img src = {{uri: item.coverUrl}} alt=""/>
<h3>{item.title}</h3>
</section>
)
});
return (
<section>
{blogItem}
<Pagination
total={this.state.total}
pageSize = {this.pageSize}
goToPage = {(pageNum) => this.goToPage(pageNum)}
/>
</section>
)
}
}
export default Test;
最后
寫的不是很好挨下,還請大家多多包涵熔恢。