如何在Ant Design嵌套表格中传递选中行的值
解决方案:Ant Design嵌套表格父子表行选择及API载荷构造
一、手动维护选中状态
用React状态维护父子表的选中关系,规避Ant Design默认行选择的局限性,尤其适配无指定唯一键的场景:
import { useState } from 'react'; const [selectedItems, setSelectedItems] = useState({}); // 结构示例:{ 父项标识: [选中的子项标识列表] }
二、分别处理父子表的行选择逻辑
父表行选择配置
给父表的rowSelection绑定自定义onChange,同步更新父项的选中状态:
const handleParentSelect = (selectedRowKeys, selectedRows) => { const newSelected = { ...selectedItems }; // 新增/保留选中的父项,初始化其子项集合 selectedRows.forEach(row => { newSelected[row.id || row.index] = newSelected[row.id || row.index] || []; }); // 删除未选中的父项 Object.keys(newSelected).forEach(key => { if (!selectedRowKeys.includes(key)) { delete newSelected[key]; } }); setSelectedItems(newSelected); }; // 父表rowSelection配置 const parentRowSelection = { onChange: handleParentSelect, preserveSelectedRowKeys: true, // 防止展开/收起子表时选中状态丢失 rowKey: (row) => row.id || row.index // 用现有字段或索引作为父项标识 };
子表行选择配置
在expandedRowRender渲染子表时,绑定子表的选择事件,关联到对应父项的选中集合:
const handleChildSelect = (parentKey, selectedChildKeys) => { setSelectedItems(prev => ({ ...prev, [parentKey]: selectedChildKeys })); }; // 子表渲染函数 const expandedRowRender = (record) => { const parentKey = record.id || record.index; return ( <Table dataSource={record.children} rowSelection={{ onChange: (keys) => handleChildSelect(parentKey, keys), rowKey: (row, idx) => `${parentKey}-child-${idx}` // 用父标识+子索引生成唯一key }} columns={childColumns} pagination={false} /> ); };
三、构造API请求载荷
根据后端要求的格式,把selectedItems转换成对应的请求体:
const buildApiPayload = () => { // 示例:转换成包含父项和选中子项的数组结构 return Object.entries(selectedItems).map(([parentKey, childKeys]) => ({ parentId: parentKey, selectedChildIds: childKeys })); }; // 提交数据到API const submitToApi = async () => { const payload = buildApiPayload(); try { // 替换成你的API请求逻辑 await fetch('/api/submit-selected', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); // 处理成功逻辑 } catch (err) { // 处理错误 } };
四、注意事项
- 如果父子表都没有唯一ID字段,用父项标识+子项索引生成
rowKey,确保每行key唯一,避免选择状态混乱。 - 若需要父表全选时自动选中所有子项,可在
handleParentSelect中遍历父项的children数组,把所有子项标识加入对应集合。 - 测试展开/收起子表时的选中状态是否稳定,若有丢失,检查
preserveSelectedRowKeys是否开启。
内容的提问来源于stack exchange,提问作者Kiran Balaji
相关产品推荐
相关产品推荐

