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

如何实现点击antd表格行内按钮时仅当前行切换为Spin加载状态

实现方案

问题核心

原有实现使用全局布尔状态控制加载态,所有行的按钮渲染都读取同一个状态值,因此触发状态变更后所有行的按钮都会被替换为Spin。只需将加载状态关联到行的唯一标识即可实现仅当前行显示加载的效果。


单条行同时加载(同一时间仅允许一行处于加载态)

1. 调整状态定义

将原有的全局布尔加载状态替换为存储当前加载行唯一标识的状态:

import { useState } from 'react';
// 替换原有的const [pending, setPending] = useState(false)
const [loadingRowId, setLoadingRowId] = useState(null);

2. 修改列配置的render逻辑

const columns = [
  // 其他列配置保持不变
  {
    title: "button",
    dataIndex: "key",
    render: (text, record) => {
      // 判断当前行是否为加载中状态,record.id为行数据的唯一标识字段,可替换为你业务中的key、id等字段
      if (loadingRowId === record.id) {
        return <Spin />
      }
      return (
        <Button
          icon={<DeleteOutlined />}
          onClick={async () => {
            // 点击时将当前行id存入状态,触发渲染Spin
            setLoadingRowId(record.id);
            try {
              // 这里写你原有的业务逻辑,比如删除请求、状态切换等
              await yourBusinessLogic(record);
            } finally {
              // 业务逻辑执行完成后重置状态,恢复按钮显示
              setLoadingRowId(null);
            }
          }}
        />
      );
    }
  }
];

3. 补充Table配置

确保给Table组件指定rowKey属性,绑定行的唯一标识字段,和状态判断的字段保持一致:

<Table
  columns={columns}
  dataSource={dataSource}
  rowKey="id" // 和上面判断用的record.id对应
/>

多条行同时加载(允许多行同时处于加载态)

如果业务需要支持同时点击多个按钮都显示加载,可使用Set存储所有加载中的行标识:

1. 调整状态定义

const [loadingRowIds, setLoadingRowIds] = useState(new Set());

2. 修改列配置的render逻辑

const columns = [
  // 其他列配置保持不变
  {
    title: "button",
    dataIndex: "key",
    render: (text, record) => {
      if (loadingRowIds.has(record.id)) {
        return <Spin />
      }
      return (
        <Button
          icon={<DeleteOutlined />}
          onClick={async () => {
            // 新增当前行id到加载集合
            const newLoadingIds = new Set(loadingRowIds);
            newLoadingIds.add(record.id);
            setLoadingRowIds(newLoadingIds);
            try {
              await yourBusinessLogic(record);
            } finally {
              // 业务执行完成后从集合中移除当前行id
              const newLoadingIds = new Set(loadingRowIds);
              newLoadingIds.delete(record.id);
              setLoadingRowIds(newLoadingIds);
            }
          }}
        />
      );
    }
  }
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:45:04