要在antd表格中每一条数据下新增一条自定义可编辑行,可以通过设置expandedRowRender属性来实现。expandedRowRender属性接收一个函数,该函数返回一个React节点,用于渲染自定义行。

具体步骤如下:

  1. 在表格的columns属性中添加一个操作列,用于触发展开/收起自定义行的功能。例如,可以使用ExpandOutlined图标作为展开按钮。
import { Table, Button } from 'antd';
import { ExpandOutlined } from '@ant-design/icons';

const columns = [
  // 其他列...
  {
    title: '操作',
    key: 'expand',
    render: (text, record) => (
      <Button
        type="link"
        icon={<ExpandOutlined />}
        onClick={() => handleExpandRow(record.id)}
      />
    ),
  },
];
  1. 在表格组件中添加一个expandedRowRender属性,并定义一个函数来渲染自定义行。在函数中,可以使用表格的dataSource属性中的数据来动态渲染自定义行的内容。
const expandedRowRender = (record) => (
  <div>
    <p>自定义行内容</p>
    <p>可以使用表格数据:{record.name}</p>
    {/* 添加自定义样式 */}
    <p style={{ color: 'red' }}>自定义行样式</p>
  </div>
);

const TableComponent = () => (
  <Table
    columns={columns}
    dataSource={data}
    expandedRowRender={expandedRowRender}
  />
);
  1. 在点击展开按钮时,通过处理函数handleExpandRow来控制表格中每一条数据对应的自定义行的展开/收起状态。
const [expandedRows, setExpandedRows] = useState([]);

const handleExpandRow = (id) => {
  let newExpandedRows = [...expandedRows];
  const index = newExpandedRows.indexOf(id);

  if (index > -1) {
    newExpandedRows = newExpandedRows.filter((rowId) => rowId !== id);
  } else {
    newExpandedRows.push(id);
  }

  setExpandedRows(newExpandedRows);
};
  1. 最后,根据自定义行的展开/收起状态,使用rowClassName属性为自定义行添加不同的样式。
const rowClassName = (record) => {
  return expandedRows.includes(record.id) ? 'expanded-row' : '';
};

const TableComponent = () => (
  <Table
    columns={columns}
    dataSource={data}
    expandedRowRender={expandedRowRender}
    rowClassName={rowClassName}
  />
);

通过以上步骤,就可以在antd表格中每一条数据下新增一条自定义可编辑行,并且可以修改自定义行的样式

antd表格每一条数据下新增一条自定义可编辑行且可以修改自定义行的样式

原文地址: https://www.cveoy.top/t/topic/hy8f 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录