默认表格展示:
展示目标:
antd
: ^5.14.1react
: ^18const columns = [
{
title: "品牌",
dataIndex: "brand",
key: "brand",
width: 100,
},
{
title: "Star",
dataIndex: "star",
key: "star",
width: 100,
}
];
const dataSource = [
{
key: "1",
brand: "logitech",
star: 4.3
},
{
key: "2",
brand: "NexiGo",
star: 3.1
},
{
key: "3",
brand: "logitech2",
star: 4.3
},
{
key: "4",
brand: "NexiGo2",
star: 3.1
},
{
key: "5",
brand: "NexiGo3",
star: 3.1
},
{
key: "6",
brand: "NexiGo4",
star: 3.1
},
{
key: "7",
brand: "NexiGo5",
star: 3.1
},
{
key: "8",
brand: "NexiGo6",
star: 3.1
},
];
import type { TableProps } from "antd";
import { useEffect, useState } from "react";
import { Table } from "antd";
import { transformData } from "./unit";
type Props = {
dataSource: any[];
columns: string[];
};
export const TestTable = function (props: Props) {
const [tableList, setTableList] = useState<any>([]);
const [tableColumns, setTableColumns] = useState<any[]>([]);
useEffect(() => {
const { columns, data } = transformData(props.dataSource);
setTableColumns(columns)
setTableList(data);
}, []);
return (
<Table
columns={tableColumns}
dataSource={tableList}
bordered
scroll={{ x: "100%", y: "auto" }}
showHeader={true}
pagination={false}
/>
);
};
export default TestTable;
数据转换:
// file: ./unit.ts
export function transformData(originalData: any[]) {
let keys = Object.keys(originalData[0]).filter((key) => key !== "key");
let columns = [{ title: "first", dataIndex: "first", key: "first" }];
originalData.forEach((key, index) => {
columns.push({
title: `col${index + 1}`,
dataIndex: `col${index + 1}`,
key: `col${index + 1}`,
});
});
let transformedData = keys.map((key, index) => {
let rowData: any = { key: `${index + 1}` };
originalData.forEach((item, idx) => {
rowData[`col${idx + 1}`] = item[key];
});
rowData.first = key;
return rowData;
});
return { columns, data: transformedData };
}