插件窝 干货文章 Ant Design Table展开行后如何修改同一行其他列的样式?

Ant Design Table展开行后如何修改同一行其他列的样式?

expandedRowRende rowClassName 样式 record 942    来源:    2025-03-24

在 Ant Design 的 Table 组件中,当你展开某一行时,你可能希望修改同一行其他列的样式。你可以通过 rowClassNameexpandedRowRender 属性来实现这一点。

1. 使用 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; /* 修改文字颜色 */
}

2. 使用 expandedRowRender 动态修改展开行的样式

expandedRowRender 是一个函数,它返回展开行的内容。你可以在这个函数中返回一个带有特定样式的元素。

const expandedRowRender = (record) => {
  return (
    <div style={{ backgroundColor: '#f0f0f0', padding: '16px' }}>
      <p>More info about {record.name}</p>
    </div>
  );
};

3. 结合 rowClassNameexpandedRowRender

你可以结合 rowClassNameexpandedRowRender 来实现更复杂的样式控制。

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}
  />
);

总结

通过 rowClassNameexpandedRowRender,你可以灵活地控制 Ant Design Table 中展开行的样式。rowClassName 用于动态设置行的类名,而 expandedRowRender 用于自定义展开行的内容及其样式。