在 Ant Design 的 Table 组件中,当你展开某一行时,你可能希望修改同一行其他列的样式。你可以通过 rowClassName
和 expandedRowRender
属性来实现这一点。
rowClassName
动态设置行样式rowClassName
是一个函数,它可以根据行的数据或状态动态返回类名。你可以利用这个属性来为展开的行设置特定的样式。
import React from 'react';
import { Table } from 'antd';
const dataSource = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
];
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
];
const expandedRowRender = (record) => {
return <p>More info about {record.name}</p>;
};
const rowClassName = (record, index) => {
// 假设你有一个状态来跟踪哪些行是展开的
const expandedRowKeys = ['1']; // 这里假设 key 为 '1' 的行是展开的
if (expandedRowKeys.includes(record.key)) {
return 'expanded-row';
}
return '';
};
const App = () => (
<Table
dataSource={dataSource}
columns={columns}
expandable={{
expandedRowRender,
}}
rowClassName={rowClassName}
/>
);
export default App;
在 CSS 中定义 .expanded-row
类:
.expanded-row td {
background-color: #f0f0f0; /* 修改背景颜色 */
color: #1890ff; /* 修改文字颜色 */
}
expandedRowRender
动态修改展开行的样式expandedRowRender
是一个函数,它返回展开行的内容。你可以在这个函数中返回一个带有特定样式的元素。
const expandedRowRender = (record) => {
return (
<div style={{ backgroundColor: '#f0f0f0', padding: '16px' }}>
<p>More info about {record.name}</p>
</div>
);
};
rowClassName
和 expandedRowRender
你可以结合 rowClassName
和 expandedRowRender
来实现更复杂的样式控制。
const expandedRowRender = (record) => {
return (
<div style={{ backgroundColor: '#f0f0f0', padding: '16px' }}>
<p>More info about {record.name}</p>
</div>
);
};
const rowClassName = (record, index) => {
const expandedRowKeys = ['1']; // 这里假设 key 为 '1' 的行是展开的
if (expandedRowKeys.includes(record.key)) {
return 'expanded-row';
}
return '';
};
const App = () => (
<Table
dataSource={dataSource}
columns={columns}
expandable={{
expandedRowRender,
}}
rowClassName={rowClassName}
/>
);
通过 rowClassName
和 expandedRowRender
,你可以灵活地控制 Ant Design Table 中展开行的样式。rowClassName
用于动态设置行的类名,而 expandedRowRender
用于自定义展开行的内容及其样式。