【前端项目——分页器】手写分页器实现(JS / React)
以下是一个简单的分页器实现,使用JavaScript和React。
import React, { useState } from 'react';
import PropTypes from 'prop-types';
const Pagination = ({ itemsCount, pageSize }) => {
const [currentPage, setCurrentPage] = useState(1);
const goToPage = (page) => {
if (page < 1 || page > Math.ceil(itemsCount / pageSize)) return;
setCurrentPage(page);
};
const handlePreviousClick = () => goToPage(currentPage - 1);
const handleNextClick = () => goToPage(currentPage + 1);
const pagesCount = Math.ceil(itemsCount / pageSize);
const pages = Array.from({ length: pagesCount }, (_, i) => i + 1);
return (
<div>
<button disabled={currentPage === 1} onClick={handlePreviousClick}>
Previous
</button>
{pages.map((page) => (
<button
key={page}
onClick={() => goToPage(page)}
style={{ backgroundColor: currentPage === page ? 'blue' : 'white' }}
>
{page}
</button>
))}
<button disabled={currentPage === pagesCount} onClick={handleNextClick}>
Next
</button>
</div>
);
};
Pagination.propTypes = {
itemsCount: PropTypes.number.isRequired,
pageSize: PropTypes.number.isRequired,
};
export default Pagination;
在这个例子中,我们创建了一个名为Pagination
的React组件,它接受itemsCount
(总项目数)和pageSize
(每页项目数)作为props。组件状态包含当前currentPage
,并提供了goToPage
方法来更新这个状态。handlePreviousClick
和handleNextClick
方法用来处理上一页和下一页的点击事件。最后,我们生成页面按钮并根据当前页设置样式。
评论已关闭