[{id: 5, amount: 2, pool: 1, name: '王哲林} {id: 3, amount: 200, pool: 3, name: '贺希宁'} {id: 2, amount: 200, pool: 2, name: '史鸿飞'} {id: 1, amount: 100, pool: 1, name: '张宁'}]数组根据pool值得不同渲染分别渲染几个table表格的例子 使用react hooks+antd的table
时间: 2024-03-16 10:45:28 浏览: 21
好的,以下是一个使用React Hooks和Antd的Table组件,根据pool值渲染不同table表格的例子代码:
```jsx
import React, { useState, useMemo } from 'react';
import { Table } from 'antd';
const dataSource = [
{ id: 5, amount: 2, pool: 1, name: '王哲林' },
{ id: 3, amount: 200, pool: 3, name: '贺希宁' },
{ id: 2, amount: 200, pool: 2, name: '史鸿飞' },
{ id: 1, amount: 100, pool: 1, name: '张宁' },
];
function App() {
const [columns] = useState([
{ title: 'ID', dataIndex: 'id', key: 'id' },
{ title: 'Name', dataIndex: 'name', key: 'name' },
]);
const dataByPool = useMemo(() => {
// 根据pool值将数据分组
return dataSource.reduce((result, item) => {
const poolData = result[item.pool] || [];
poolData.push(item);
result[item.pool] = poolData;
return result;
}, {});
}, []);
return (
<>
{Object.keys(dataByPool).map((pool, index) => (
<Table
key={index}
dataSource={dataByPool[pool]}
columns={columns}
title={() => `Pool ${pool}`}
/>
))}
</>
);
}
export default App;
```
在上面的代码中,我们首先定义了一个数据源 `dataSource`,然后使用 `useState` 定义了一个 `columns` 状态,存储了表格的列信息。接着,我们使用 `useMemo` 将数据源根据 pool 值分组,得到一个以 pool 值为键,以数据项为值的对象。最后,我们使用 `Object.keys` 遍历这个对象,渲染对应的 table 表格。其中,每个表格的标题为 `Pool` 后面跟着该表格的 pool 值,表格中的数据则是该 pool 值下的所有数据项。
下面是完整的React Hooks和Antd的Table组件示例代码:
```jsx
import React, { useState, useMemo } from 'react';
import { Table } from 'antd';
const dataSource = [
{ id: 5, amount: 2, pool: 1, name: '王哲林' },
{ id: 3, amount: 200, pool: 3, name: '贺希宁' },
{ id: 2, amount: 200, pool: 2, name: '史鸿飞' },
{ id: 1, amount: 100, pool: 1, name: '张宁' },
];
function App() {
const [columns] = useState([
{ title: 'ID', dataIndex: 'id', key: 'id' },
{ title: 'Name', dataIndex: 'name', key: 'name' },
]);
const dataByPool = useMemo(() => {
// 根据pool值将数据分组
return dataSource.reduce((result, item) => {
const poolData = result[item.pool] || [];
poolData.push(item);
result[item.pool] = poolData;
return result;
}, {});
}, []);
return (
<>
{Object.keys(dataByPool).map((pool, index) => (
<Table
key={index}
dataSource={dataByPool[pool]}
columns={columns}
title={() => `Pool ${pool}`}
/>
))}
</>
);
}
export default App;
```
运行这个示例代码,你会看到页面上渲染出了三个 Table 表格,分别显示了 pool 值为 1、2、3 的数据项。