const [expandedRowKeys, setExpandedRowKeys] = useState<any>([]); //当前展开行的key
//设置当前展开的key
const handleExpand = (record:any) => {
console.log(record)
const newExpandedRowKeys = [record.key];
setExpandedRowKeys(newExpandedRowKeys);
};
//监听展开行
const handleExpandIconClick = (expanded:any, record:any) => {
console.log(expanded,record)
if (expanded) {
handleExpand(record); // 展开当前行
} else {
setExpandedRowKeys([]); // 关闭所有展开的行
}
};
//表格配置
const expandable = {
expandedRowKeys: expandedRowKeys, // 当前行key
onExpand: handleExpandIconClick, // 点击当前行的操作
};
//columns 表头
//tableData 表格数据
// 返回数据。每一条如果有children 。会直接识别子表格。 不用特意操作。
//expandable 表格配置
<div>
<Table
columns={columns}
dataSource={tableData}
expandable={expandable}
loading={loading}
scroll={{ x: 1200 }}
style={{ width: '100%' }}
size="small"
bordered
pagination={false}
/>
</div>
基本就可以直接完成操作了
如果表格第一列等有其他操作。 例如多加一个按钮。进行切换数据等 。
// 通过函数判断一个值是否为负数
const isNegative = (num: string) => {
if (num && num.indexOf('%') != -1) {
let newNum = num.slice(0, -1)
return Number(newNum) < 0;
} else {
return Number(num) < 0;
}
}
//判断是否是第一列。 是否有展开的子表格
// 处理表头的render函数
const jsxFnTitle =(text:any,record:any,index:any,item:any) =>{
return (
<div>
{item.dataIndex=='project_name'&&record.allow_switch == 1? (
<Row>
<Col span={17}><span>{text}</span> </Col>
<Col span={5}> <RetweetOutlined className='switch_btn' onClick={()=>clickBtn(record)}/>切换数据按钮 </Col>
<Col span={2}> </Col>
</Row>
) : (
isNegative(text) ? (
<span className='red'>{text}</span>
) : (
<span>{text}</span>
)
)}
</div>
);
}
const { loading, run } = useRequest(GET_DATA, {
manual: true,
onSuccess: (data: { code: number; msg: string; result: any }) => {
if (data.code != 0) {
return;
}
console.log(data.result.title,'表头数据 ')
console.log(data.result.body ,'表体数据 ')
let newTitle = data.result.title.map((item: any, index: number) => {
if (index == 0) {
item.width = 200 // 定义第一列的宽度
}
if (index == data.result.title.length - 1) {
item.width = 120 // 定义最后一列的宽度
}
item.render = (text: any,record:any,index:any) => jsxFnTitle(text,record,index,item) // render函数的处理
return item
})
setColumns(newTitle) // 设置表头
setTimeout(() => {
setTableData(data.result.body) // 设置表体
}, 100);
},
}
)