Files
leaudit-platform-frontend/app/components/ui/Table.tsx
T
2025-04-16 18:47:22 +08:00

109 lines
3.2 KiB
TypeScript

import React from 'react';
interface TableColumn<T> {
title: React.ReactNode;
dataIndex?: keyof T;
key?: string;
width?: number | string;
render?: (value: any, record: T, index: number) => React.ReactNode;
align?: 'left' | 'center' | 'right';
className?: string;
}
interface TableProps<T> {
columns: TableColumn<T>[];
dataSource: T[];
rowKey: keyof T | ((record: T) => string);
loading?: boolean;
bordered?: boolean;
emptyText?: React.ReactNode;
className?: string;
onRow?: (record: T, index: number) => React.HTMLAttributes<HTMLTableRowElement>;
}
export function Table<T extends Record<string, any>>({
columns,
dataSource,
rowKey,
loading = false,
bordered = false,
emptyText = '暂无数据',
className = '',
onRow,
}: TableProps<T>) {
const getRowKey = (record: T, index: number): string => {
if (typeof rowKey === 'function') {
return rowKey(record);
}
return String(record[rowKey]);
};
return (
<div className={`ant-table-wrapper ${className} ${loading ? 'ant-table-loading' : ''}`}>
<table className={`ant-table ${bordered ? 'ant-table-bordered' : ''}`}>
<thead>
<tr>
{columns.map((column, index) => (
<th
key={column.key || column.dataIndex?.toString() || index}
className={column.className}
style={{
width: column.width,
textAlign: column.align || 'left',
}}
>
{column.title}
</th>
))}
</tr>
</thead>
<tbody>
{dataSource.length > 0 ? (
dataSource.map((record, index) => (
<tr
key={getRowKey(record, index)}
{...(onRow ? onRow(record, index) : {})}
>
{columns.map((column, colIndex) => (
<td
key={column.key || column.dataIndex?.toString() || colIndex}
style={{ textAlign: column.align || 'left' }}
>
{column.render
? column.render(
column.dataIndex ? record[column.dataIndex] : undefined,
record,
index
)
: column.dataIndex
? record[column.dataIndex]
: undefined}
</td>
))}
</tr>
))
) : (
<tr>
<td
colSpan={columns.length}
className="ant-table-empty py-6 text-center text-gray-500"
>
{emptyText}
</td>
</tr>
)}
</tbody>
</table>
{loading && (
<div className="ant-table-loading-indicator">
<div className="flex items-center space-x-2">
<div className="w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
<span className="text-gray-600">...</span>
</div>
</div>
)}
</div>
);
}