1 import React, { useState, useEffect } from 'react'; 2 import { Tabs } from 'antd'; 3 import AComponent from './components/AComponent'; 4 import BComponent from './components/BComponent'; 5 6 const CComponent = () => { 7 const [currentTabKey, setCurrentTabKey] = useState('a'); 8 const [selectedItemsFromA, setSelectedItemsFromA] = useState<any[]>([]); 9 10 const handleTabChange = (key: string) => { 11 setCurrentTabKey(key); 12 }; 13 14 const handleSelectedItemsChange = (items: any[]) => { 15 setSelectedItemsFromA(items); 16 }; 17 18 useEffect(() => { 19 // 在首次渲染或当前Tab切换到'B'时,确保已获取最新的selectedItemsFromA 20 if (currentTabKey === 'b') { 21 // 这里无需额外操作,因为在handleSelectedItemsChange中已经同步了数据 22 } 23 }, [currentTabKey]); 24 25 return ( 26 <Tabs onChange={handleTabChange} activeKey={currentTabKey}> 27 <Tabs.TabPane key="a" tab="Tab A"> 28 <AComponent onSelectedItemsChange={handleSelectedItemsChange} /> 29 </Tabs.TabPane> 30 <Tabs.TabPane key="b" tab="Tab B"> 31 <BComponent selectedItems={selectedItemsFromA} /> 32 </Tabs.TabPane> 33 </Tabs> 34 ); 35 }; 36 37 export default CComponent;
子组件
// AComponent.tsx import React, { useState } from 'react'; import { Table } from 'antd'; const AComponent = (props: { onSelectedItemsChange: (items: any[]) => void }) => { const [tableData, setTableData] = useState<any[]>([]); // 假设这是表格的数据 const handleSelectionChange = (selectedRowKeys: React.Key[], selectedRows: any[]) => { props.onSelectedItemsChange(selectedRows); }; return ( <Table rowKey={(record) => record.key} // 确保每行有唯一的key值 dataSource={tableData} rowSelection={{ onChange: handleSelectionChange, // 其他配置... }} // ...其他表格配置项 /> ); }; export default AComponent;