帮我用react+antdesign实现一个表格嵌套两层表格的效果,以class MonitorList extends React.Component命名
时间: 2024-02-23 12:02:54 浏览: 122
Element实现表格嵌套、多个表格共用一个表头的方法
好的,以下是一个简单的实现示例:
```javascript
import React from 'react';
import { Table } from 'antd';
class MonitorList extends React.Component {
state = {
dataSource: [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
children: [
{
key: '11',
name: 'John Brown Jr.',
age: 18,
address: 'New York No. 2 Lake Park',
},
{
key: '12',
name: 'John Brown Sr.',
age: 45,
address: 'New York No. 3 Lake Park',
children: [
{
key: '121',
name: 'John Brown',
age: 18,
address: 'New York No. 3 Lake Park',
},
{
key: '122',
name: 'Mike Brown',
age: 25,
address: 'New York No. 4 Lake Park',
},
],
},
],
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
children: [
{
key: '21',
name: 'Jim Green Jr.',
age: 18,
address: 'London No. 2 Lake Park',
},
{
key: '22',
name: 'Jimmy Green Sr.',
age: 45,
address: 'London No. 3 Lake Park',
children: [
{
key: '221',
name: 'Jim Green',
age: 18,
address: 'London No. 3 Lake Park',
},
{
key: '222',
name: 'Jenny Green',
age: 25,
address: 'London No. 4 Lake Park',
},
],
},
],
},
],
columns: [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
],
};
render() {
const { dataSource, columns } = this.state;
const renderNestedTable = (record) => {
const nestedColumns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
];
return (
<Table
columns={nestedColumns}
dataSource={record.children}
pagination={false}
size="small"
/>
);
};
return (
<Table
columns={columns}
dataSource={dataSource}
expandedRowRender={renderNestedTable}
/>
);
}
}
export default MonitorList;
```
这个示例使用了Ant Design的Table组件实现了一个表格嵌套两层表格的效果。其中,外层表格的数据源为一个包含嵌套子数据的数组,内层表格的数据源则为嵌套子数据的`children`字段,通过在外层表格中设置`expandedRowRender`属性为一个函数,可以在每一行展开时自动渲染内层表格。
阅读全文