You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ant Design Table自定义展开图标异常:不符合条件行仍显示

Ant Design v5 Table自定义展开图标时,不符合条件的行仍显示图标问题解决

问题场景

使用Ant Design v5的Table组件,通过expandable.rowExpandable配置项设置仅user_role > 1的行可展开:

  • 使用默认展开图标时,仅符合条件的行显示图标,表现正常;
  • 使用@ant-design/icons提供的自定义图标时,所有行都会显示图标,无视rowExpandable的判断条件。

问题原因

当自定义expandIcon时,Ant Design不会自动依据rowExpandable的结果控制图标的显示,需要开发者手动在expandIcon函数中添加行可展开性的判断逻辑。

解决方案

在自定义expandIcon的逻辑中,先判断当前行是否满足可展开条件,若不满足则返回null(不渲染图标),否则再渲染对应的展开/收起图标。

修改后的完整代码如下:

import React from "react";
import ReactDOM from "react-dom";
import { PlusCircleTwoTone, MinusCircleTwoTone } from "@ant-design/icons";
import "antd/dist/antd.css";
import "./index.css";
import { Table } from "antd";

const columns = [
  { title: "Name", dataIndex: "name", key: "name" },
  { title: "Age", dataIndex: "age", key: "age" },
  { title: "Address", dataIndex: "address", key: "address" },
  {
    title: "Action",
    dataIndex: "",
    key: "x",
    render: () => <a href='https://www.google.com'>Delete</a>
  }
];

const data = [
  {
    key: 1,
    user_role: 3,
    name: "John Brown",
    age: 32,
    address: "New York No. 1 Lake Park",
    description:
      "My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park."
  },
  {
    key: 2,
    user_role: 3,
    name: "Jim Green",
    age: 42,
    address: "London No. 1 Lake Park",
    description:
      "My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park."
  },
  {
    key: 3,
    user_role: 1,
    name: "Not Expandable",
    age: 29,
    address: "Jiangsu No. 1 Lake Park",
    description: "This not expandable"
  },
  {
    key: 4,
    user_role: 3,
    name: "Joe Black",
    age: 32,
    address: "Sidney No. 1 Lake Park",
    description:
      "My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park."
  }
];

ReactDOM.render(
  <Table
    columns={columns}
    dataSource={data}
    expandable={{
      expandedRowRender: record => (
        <p style={{ margin: 0 }}>{record.description}</p>
      ),
      rowExpandable: (record) => record.user_role > 1,
      expandIcon: ({ expanded, onExpand, record }) => {
        // 手动判断当前行是否可展开
        const canExpand = record.user_role > 1;
        if (!canExpand) {
          return null;
        }
        return expanded ? (
          <MinusCircleTwoTone onClick={e => onExpand(record, e)} />
        ) : (
          <PlusCircleTwoTone onClick={e => onExpand(record, e)} />
        );
      }
    }}
  />,
  document.getElementById("container")
);

效果说明

修改后,只有满足user_role > 1的行才会显示自定义的展开/收起图标,与默认图标的表现一致,不符合条件的行不再显示图标。

内容的提问来源于stack exchange,提问作者A_M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:05:13