使用了React框架封装了一个分页器
类似于element的分页器,不过没有他们的完善,实现了基础的功能,主要是对于react组件化封装的一个理解,以及父子组件传值的理解 以下是代码
这是父组件
import React, { useState } from 'react'
import CgPagination from './components/page/CgPagination'
export default function page() {
const [total, setTotal] = useState(55) // 总条数
const [pageSize, setPageSize] = useState(10) // 每页多少条
const [currentPage, setCurrentPage] = useState(1) // 当前页
// 页码发生变化
const changePage = (page) => {
setCurrentPage(page)
}
return (
<>
<p>分页器</p>
<CgPagination
total={total}
pageSize={pageSize}
currentPage={currentPage}
changePage={changePage}
>
</CgPagination>
</>
)
}
子组件
import React, { useState } from 'react'
import './CgPagination.scss'
export default function CgPagination(props) {
let { total, pageSize, currentPage, changePage } = props
// 获取所有的页码列表 用一个数组存起来
const pageList = []
const getPageList = () => {
// 获取总页数
let pageNum = Math.ceil(total / pageSize)
for (let i = 1; i <= Math.ceil(total / pageSize); i++) {
pageList.push(i)
}
}
getPageList() //调用
// 点击切换下一页
const nextBtn = () => {
// 如果当前页码不是最后一个就可以继续点击 下一页
if (currentPage < Math.ceil(total / pageSize)) {
changePage(currentPage + 1)
}
}
// 点击切换上一页
const perBtn = () => {
// 同上判断 当前页码必须>1才能点击
if (currentPage > 1) {
changePage(currentPage - 1)
}
}
// 在输入框直接修改页码
const editPage = (e) => {
changePage(e.target.value)
}
// 直接点击页码切换
const selectPage = (page) => {
changePage(page)
}
return (
<>
<div className='pagination'>
<p>总条数:{total}</p>
<button onClick={perBtn}>上一页</button>
{
pageList.map((item, index) => <div
className={currentPage == item ? 'active' : ''}
key={index}
onClick={() => selectPage(item)}
>{item}</div>)
}
<button onClick={nextBtn}>下一页</button>
<p>当前页: <input type="text" value={currentPage} onChange={(e) => editPage(e)} /></p>
</div>
</>
)
}
子组件scss样式文件
.pagination {
display: flex;
&>div {
width: 30px;
height: 30px;
text-align: center;
line-height: 30px;
margin: 0 10px;
cursor: pointer;
border-radius: 10px;
}
.active {
color: #a0c6e8;
box-shadow: 0 0 10px 0#ccc;
}
}