前言
分頁其實很容易實現,我自己寫了一個簡單的分頁組件,可以實現上下翻頁,輸入頁碼跳轉到指定頁,刷新頁面後不會回到第一頁(hash值記錄當前頁碼)。效果如下:
功能分析
把這個組件拆開看,其實就是三個功能:
- 翻頁(基本功能)
- 跳轉到指定頁
- 記錄頁碼(利用hash)
父組件向分頁組件需要傳遞兩個值:數據總數,一頁顯示幾條數據。
<Pagination
total={this.state.total}
pageSize = {this.pageSize}
/>
翻頁功能實現
分頁組件:
constructor(props) {
super(props);
this.state = {
currentPageNum: props.currentPageNum, //當前頁碼
}
}
render() {
let pageTotal = Math.ceil(this.props.total / this.props.pageSize); //頁碼總數
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>
)
}
}
當前頁碼currentPageNum
是從父組件傳遞過來的值,一般情況下不需要傳這個值,我之前是從父組件更改它,後來修改了代碼,就在組件裏更新它,不過父組件也可以傳當前頁碼過來。
到這裏就完成了基本的分頁組件展示了,接下來開始實現上一頁和下一頁功能。
給上一頁和下一頁綁定事件:
<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()是子組件調用父組件傳過來的方法。點擊翻頁的時候,子組件也需要向父組件傳參,並調用該方法,通過回調函數就實現了子組件向父組件傳值。
父組件要傳遞這個函數:
<Pagination
total={this.state.total}
pageSize = {this.pageSize}
currentPageNum = {this.state.currentPageNum}
goToPage = {(pageNum) => this.goToPage(pageNum)}
/>
這裏父組件就可以獲取到翻頁子組件傳過來的頁碼,然後根據這個頁碼發起網絡請求,這裏怎麼寫和後臺有關,比如我們的後臺是有分頁的,我要請求第幾頁,請求多少條數據傳遞給後臺就可以,可能有的後臺是返回了全部數據,然後前端去處理分頁,那就不是發起網絡請求,而是將當前顯示的數據index往後移 當前頁碼currentPageNum * 一頁顯示數據條數pageSize
這麼多位置,以實現翻頁效果。
父組件的翻頁事件:
//翻頁
goToPage(pageNum) {
this.requestNewsData(pageNum); //網絡請求的方法
}
以上短短几行代碼就實現了翻頁,不過還不夠完善,比如我並沒有對上一頁和下一頁按鈕做限制,即如果當前是第一頁和最後一頁就不能再觸發goToPage()方法了,所以我應該在goToPage()裏面去判斷當前頁碼是否是第一頁或者最後一頁,這裏我採用了另一種方式。
注意看頁面按鈕是有兩種狀態,當不可點擊時箭頭是灰色的,大部分翻頁都有這個效果,我覺得最好的方式是使用兩種標籤:可點擊狀態的<a>
標籤和不可點擊的<span>
標籤,使用三目運算符做判斷,這樣就保證了currentPageNum-1或者+1都不會越界。
以下是對上一頁按鈕做的處理:
//nextBtnDisabled是不可點擊狀態的圖標,nextBtn是可點擊狀態的圖標
{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
,我覺得在這裏做判斷是最簡單的做法,這樣無需考慮頁碼越界的問題,而且視覺上也讓用戶體驗更好。
輸入頁碼跳轉到指定頁功能實現
給input框綁定事件:
<input
type="text"
value={this.state.currentPageNum}
onChange={this.changePageNumber.bind(this)}
onKeyUp={(event) => this.handleKeyUp(event, pageTotal)}
/>
onChange事件當輸入框值發生變化時被觸發,輸入框的值即當前頁碼
//頁碼輸入框
changePageNumber(event) {
this.setState({
currentPageNum: event.target.value
});
}
onKeyUp事件是鍵盤按下事件,我是在按下回車鍵的時候觸發更新,另外,也需要做判斷,判斷是否是合法的頁碼:
//鍵盤按下事件,pageTotal是頁碼數
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() 不是一個數字返回true
alert('請輸入數字!')
} else if(value > pageTotal || value === null || value.trim() === '') { //使用trim()去掉空格,全爲空格的字符串不爲''也不爲null
alert('請輸入合法的頁碼')
} else {
this.goToPage(parseInt(value, 10)) //輸入了合法頁碼,調用跳轉頁面方法。
}
}
}
分頁錨點功能實現(使用react-router-dom)
一般有分頁的地方都會有錨點,記錄當前頁碼,當瀏覽器刷新或者回退時可以定位到當前頁碼,因爲我的路由用的react-router-dom,所以頁面跳轉用Link,這裏將a標籤替換成Link標籤:
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}
就是將頁碼設置爲hash值,會顯示在url地址欄中,比如:www.baidu.com#2
這種形式。這樣就實現了將頁碼作爲錨點的功能,不過要實現刷新時依然在當前頁碼,還需要在componentDidMount
裏面手動解析url將頁碼取出來然後再調用goToPage()
方法:
componentDidMount() {
this.handleAnchor() //頁面刷新時回到刷新前的page
}
handleAnchor() {
let index = window.location.hash.slice(1) || 1; //獲取hash值
this.goToPage(parseInt(index, 10));
}
最後還有輸入頁碼當頁碼合法時跳轉到指定頁也需要添加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() 不是一個數字返回true
alert('請輸入數字!')
} else if(value > pageTotal || value === null || value.trim() === '') { //使用trim()去掉空格,全爲空格的字符串不爲''也不爲null
alert('請輸入合法的頁碼')
} else {
window.location.hash = `#${value}`;
this.goToPage(parseInt(value, 10)) //這裏一定要將value類型轉換爲數字,用戶手動輸入頁碼很有可能是string。而最好在這裏轉換是因爲已經過濾了不是數字和空的值,不會出現NaN的情況
}
}
}
render() {
let pageTotal = Math.ceil(this.props.total / this.props.pageSize); //頁碼總數
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, //數據總數
pageSize: PropTypes.number, //一頁顯示幾條數據
currentPageNum: PropTypes.number, //當前頁碼
};
調用方法:
import React, { Component } from 'react';
import Pagination from '../components/pagination';
class Test extends Component {
constructor(props) {
super(props);
this.state = {
total: 0, //數據總數
data: [],
};
this.pageSize = 10; //一頁顯示的數據條數
}
//獲取數據
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;
最後
寫的不是很好,還請大家多多包涵。