Pagination.tsx 1.92 KB
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>
  );
}