本文主要和大家介绍用react来写一个分页组件(小结),希望能帮助大家学会用react来写一个分页组件,下面我们一起来学习一下吧。
效果截图(样式可自行修改):
构建项目
create-react-app react-paging-component
登录后复制
分页组件
1.子组件
创建 Pagecomponent.js 文件
核心代码:
初始化值
constructor(props) { super(props) this.state = { currentPage: 1, //当前页码 groupCount: 5, //页码分组,显示7个页码,其余用省略号显示 startPage: 1, //分组开始页码 totalPage:1 //总页数 } }
登录后复制
动态生成页码函数
createPage() { const {currentPage, groupCount, startPage,totalPage} = this.state; let pages = [] //上一页 pages.push(
登录后复制 上一页) if (totalPage {i}) } } else { /*总页码大于10时,部分显示*/ //第一页 pages.push(1) let pageLength = 0; if (groupCount + startPage > totalPage) { pageLength = totalPage } else { pageLength = groupCount + startPage; } //前面省略号(当当前页码比分组的页码大时显示省略号) if (currentPage >= groupCount) { pages.push(···) } //非第一页和最后一页显示 for (let i = startPage; i 1) { pages.push({i}) } } //后面省略号 if (totalPage – startPage >= groupCount + 1) { pages.push(···) } //最后一页 pages.push({totalPage}) } //下一页 pages.push(下一页) return pages; }
页码点击函数:
//页码点击 pageClick(currentPage) { const {groupCount} = this.state const getCurrentPage = this.props.pageCallbackFn; //当 当前页码 大于 分组的页码 时,使 当前页 前面 显示 两个页码 if (currentPage >= groupCount) { this.setState({ startPage: currentPage - 2, }) } if (currentPage上一页和夏夜点击事件
//上一页事件 prePageHandeler() { let {currentPage} = this.state if (--currentPage === 0) { return false } this.pageClick(currentPage) } //下一页事件 nextPageHandeler() { let {currentPage,totalPage} = this.state // const {totalPage} = this.props.pageConfig; if (++currentPage > totalPage) { return false } this.pageClick(currentPage) }登录后复制
组件渲染到DOM上
render() { const pageList = this.createPage(); return (登录后复制 {pageList} ) }
2.父组件
创建 Pagecontainer.js 文件
父组件完整代码
import React, {Component} from 'react'import Pagecomponent from '../components/Pagecomponent'import data from '../mock/tsconfig.json'class Pagecontainer extends Component { constructor() { super() this.state = { dataList:[], pageConfig: { totalPage: data.length //总页码 } } this.getCurrentPage = this.getCurrentPage.bind(this) } getCurrentPage(currentPage) { this.setState({ dataList:data[currentPage-1].name }) } render() { return (
{this.state.dataList}
) }}export default Pagecontainer登录后复制
相关推荐:
jQuery封装的分页组件详解
利用vue2.0实现的分页组件
基于vue2的table分页组件实现方法
以上就是用react写一个分页组件的示例的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2786546.html