曹耘豪的博客

React之生成table

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
import React from "react";

export type TableHeaderConfig<Row> = {
title: string | React.ReactElement,
key: string,
render?: (row: Row, value: any) => string | React.ReactElement,
}

export default function BaseTable<T>(props: { configs: TableHeaderConfig<T>[], rows?: any[] }) {
const {configs, rows} = props;

return <><table className="border-collapse">
<thead>
<tr>
{
configs.map((config, i) => {
return <th key={i} className="border border-slate-300 border-solid px-2 py-1 whitespace-nowrap">{config.title}</th>
})
}
</tr>
</thead>
{
rows && rows.length > 0 && <tbody>
{
rows.map((row, i) => {
return <tr key={i}>
{
configs.map((config, i) => {
const {key, render} = config
let node = render != null ? render(row, row[key]) : row[key]
return <td key={i} className="border border-slate-300 border-solid px-2 py-1 whitespace-nowrap text-center">
{
node
}
</td>
})
}
</tr>
})
}
</tbody> || null
}
</table>
</>
}
   /