一、需求
在使用Table组件嵌套Table时,父子Table的选择框需要联动,即父Table选中,该行下的子Table需要全选中,某一个子Table全部选中,则该子Table所在的父Table那一行也需要选中。
二、Table的rowSelection配置
父子Table联动,就不能使用OnChange,需要使用OnSelect以及OnSelectAll手动配置。
selectedRowKeys:指定选中项的key数组
OnSelect:手动选择/取消选择某行的回调
OnSelect(record, selected, selectedRows)
record:选中的当前行数据
selected:选中状态,true:选中,false:取消选中
selectedRows:选择的数组
OnSelectAll:手动选择/取消选择所有行的回调
OnSelect(selected, selectedRows, changeRows)
selected:选中状态,true:选中,false:取消选中
selectedRows:选择的数组
changeRows:改变的所有数组
三、根据antd文档搭建Table嵌套Table界面
import React, { useEffect, useState } from ‘react’;
import { Table, } from ‘antd’
export default () => {
const dataSource: any = [
{
key: ‘1’,
title: ‘餐饮酒店/服务员’,
number: ‘8家门店,共8人’,
time: ‘2020.05.25 15:35’,
childData: [
{
key: ‘1.1’,
jobTitle: ‘大桶大足浴-保安’,
num: ‘2人’,
},
{
key: ‘1.2’,
jobTitle: ‘大桶大足浴-保安’,
num: ‘5人’,
},
]
},
{
key: ‘2’,
title: ‘餐饮酒店/收银员’,
number: ‘无门店,共5人’,
time: ‘2020.06.06 11:35’,
childData: [
{
key: ‘2.1’,
jobTitle: ‘大桶大足浴’,
num: ‘0人’,
},
{
key: ‘2.2’,
jobTitle: ‘大桶大足浴’,
num: ‘1人’,
},
]
},
]
const parentColumns: any = [
{
title: ‘工种’,
dataIndex: ‘title’,
key: ‘title’,
},
{
title: ‘关联门店数’,
dataIndex: ‘number’,
key: ‘number’,
},
{
title: ‘时间’,
dataIndex: ‘time’,
key: ‘time’,
},
]
const expandedRowRender = (record: any, index: any, indent: any, expanded: any) => {
const childData = record.childData
const childColumns: any = [
{
title: ‘岗位名称’,
dataIndex: ‘jobTitle’,
key: ‘jobTitle’
},
{
title: ‘招聘人数’,
dataIndex: ‘num’,
key: ‘num’
},
]
return
}
return (
);
}
四、开始配置rowSelection
1、配置父子Table的rowSelection
const childRowSelection = {
selectedRowKeys: childSelectedRowKeys,
onSelect: onChildSelectChange,
onSelectAll: onChildSelectAll
}
const parentRowSelection = {
selectedRowKeys: parentSelectedRowKeys,
onSelect: onParentSelectChange,
onSelectAll: onParentSelectAll,
}
2、创建childSelectedRowKeys,parentSelectedRowKeys变量,用来存放父子Table选中的key值
const [parentSelectedRowKeys, setParent