Pagination.tsx
1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { useState } from 'react';
import styles from './Shared.module.css';
import { cx } from './utils';
export interface PaginationProps {
/** current/pageSize/total 共同描述后台列表分页状态。 */
current: number;
pageSize: number;
total: number;
pageSizeOptions?: number[];
onChange?: (page: number, pageSize: number) => void;
}
export function Pagination({ current, pageSize, pageSizeOptions = [10, 20, 50], total, onChange }: PaginationProps) {
const [jump, setJump] = useState('');
const totalPages = Math.max(1, Math.ceil(total / pageSize));
const pages = Array.from({ length: Math.min(totalPages, 5) }, (_, index) => index + 1);
const submitJump = () => onChange?.(Number(jump), pageSize);
return (
<div className={styles.between}>
<span className={styles.muted}>共 {total} 条</span>
<div className={styles.row}>
{pages.map((page) => (
<button key={page} className={cx(styles.control, page === current && styles.paginationCurrent)} type="button" aria-label={`第 ${page} 页`} aria-current={page === current ? 'page' : undefined} onClick={() => onChange?.(page, pageSize)}>
{page}
</button>
))}
<select aria-label="每页条数" className={styles.control} value={pageSize} onChange={(event) => onChange?.(1, Number(event.target.value))}>
{pageSizeOptions.map((option) => (
<option key={option} value={option}>
{option} 条/页
</option>
))}
</select>
<input
aria-label="跳至页码"
className={styles.control}
value={jump}
onChange={(event) => setJump(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') submitJump();
}}
/>
<button className={styles.control} type="button" onClick={submitJump}>
跳转
</button>
</div>
</div>
);
}