表格 Table
这是一个基于 React.forwardRef
封装的表格组件集合,提供一致的样式、结构化语义以及扩展能力,适配现代 UI 设计规范(如 shadcn/ui 风格)。
📦 引入方式
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from '@npmqg/react-ui-table';
🧩 使用示例
- 示例
- 源码
订单号 | 商品 | 金额 |
---|---|---|
#1001 | MacBook Pro | ¥ 12,999 |
#1002 | iPhone 15 | ¥ 8,999 |
总计 | ¥ 21,998 |
<Table>
<TableCaption>最近交易记录</TableCaption>
<TableHeader>
<TableRow>
<TableHead>订单号</TableHead>
<TableHead>商品</TableHead>
<TableHead>金额</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell>#1001</TableCell>
<TableCell>MacBook Pro</TableCell>
<TableCell>¥ 12,999</TableCell>
</TableRow>
<TableRow>
<TableCell>#1002</TableCell>
<TableCell>iPhone 15</TableCell>
<TableCell>¥ 8,999</TableCell>
</TableRow>
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={2}>总计</TableCell>
<TableCell>¥ 21,998</TableCell>
</TableRow>
</TableFooter>
</Table>
🧩 组件结构
组件名 | 描述 | 属性 | 类型 | 默认值 | 描述 |
---|---|---|---|---|---|
Table | 表格容器 | className | string | — | 表格容器自定义类名 |
TableHeader | <thead> 表头部分 | className | string | — | 表头部分自定义类名 |
TableBody | <tbody> 主体部分 | className | string | — | 主体部分自定义类名 |
TableFooter | <tfoot> 表尾部分 | className | string | — | 表尾部 分自定义类名 |
TableRow | <tr> 行 | className | string | — | 行自定义类名 |
data-state | string | — | 自定义样式切换 | ||
TableHead | <th> 表头单元格 | scope | string | — | 表头单元格的作用域 |
colSpan | number | — | 列跨度 | ||
rowSpan | number | — | 行跨度 | ||
TableCell | <td> 表格单元格 | className | string | — | 单元格自定义类名 |
checkbox | boolean | false | 是否嵌套 checkbox 结构,自动调整 padding | ||
TableCaption | <caption> 表格标题 | className | string | — | 表格标题自定义类名 |
🎨 默认样式特性(TailwindCSS)
📚TableRow
- 行 hover 高亮:
hover:bg-muted/50
- 支持
data-state="selected"
变色高亮:data-[state=selected]:bg-muted
📚TableHead
- 文本左对齐、字体中等、颜色淡化:
text-muted-foreground
📚TableCell
- 默认内边距:
p-2
- 若包含
role=checkbox
子元素,则自动去除右padding
🧠 设计理念
- 表格组件使用语义化 HTML 元素封装,确保无障碍(A11y)友好
- 与 Tailwind 工具类无缝结合,样式灵活、响应式良好
- 组件化拆分易于组合、扩展(如插入选择框、操作列)
💡 Tips
- 可结合
<ScrollArea>
使用,避免在固定容器中溢出 - 推荐搭配
react-table
,@tanstack/react-table
使用,实现数据驱动表格 - 若需排序、筛选、分页等功能,建议使用表格状态管理库进行扩展