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

Ant Design表格Source列如何根据设备ID动态渲染对应图标

Ant Design Table Source列动态渲染图标解决方案

现有代码问题点

  • Source列的render函数仅接收了第一个参数,未获取当前行完整数据,无法读取dev_id字段做条件判断
  • 存在重复导入React的冗余代码
  • Table组件属性名书写错误:列配置属性应为columns而非column
  • Source列的key、dataIndex设置为空字符串,不符合规范易触发渲染警告

核心修改方法

Ant Design Table列配置的render函数签名为render(text, record, index),其中第二个参数record就是当前行的完整数据对象,直接读取record.dev_id做条件判断返回对应图标即可。

修正后的Source列配置

{
    title: 'Source',
    key: "source",
    render: (_, record) => {
        switch(record.dev_id) {
            case 1:
                return <UserOutlined />;
            case 2:
                return <LaptopOutlined />;
            default:
                // 非预期dev_id的兜底逻辑,可按需调整
                return null;
        }
    }
}

其他必要修正

  1. 删除重复的React导入语句,仅保留一行import React, { useEffect, useState } from 'react';
  2. 将Table组件的属性从column={columns}修改为columns={columns},确保列配置正常生效
  3. 建议给Table增加rowKey属性指定数据唯一键,避免渲染警告

修正后的完整代码

import React, { useEffect, useState } from 'react';
import { Card, Col, Divider, Layout, Row, Table, Tag } from 'antd';
import axios from 'axios';
import { Content, Footer, Header } from 'antd/lib/layout/layout';
import 'antd/dist/antd.css';
import '../Page/Dashboard.css';
import { LaptopOutlined, UserAddOutlined, UserOutlined } from '@ant-design/icons';

const columns = [
{
    title: "No",
    dataIndex: "id",
    key: "id",
},
{
    title: 'Device ID',
    dataIndex: "dev_id",
    key: "dev_id",
},
{
    title: 'Message ID',
    dataIndex: "msg_id",
    key: "msg_id",
},
{
    title: 'Time Stamp',
    dataIndex: "time_stamp",
    key: "time_stamp",
},
{
    title: 'RFID',
    dataIndex: "rfid",
    key: "rfid",
},
{
    title: 'Data Hewan',
    dataIndex: "animals",
    key: "animals",
},
{
    title: 'Weight (kg)',
    dataIndex: "weight",
    key: "weight",
},
{
    title: 'Temperature (Celcius)',
    dataIndex: "temp",
    key: "temp",
},
{
    title: 'Tags',
    dataIndex: "tags",
    key: "tags",
    render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag === 'Invalid Data' ? 'volcano' : 'geekblue';
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
},
{
    title: 'Source',
    key: "source",
    render: (_, record) => {
        if (record.dev_id === 1) return <UserOutlined />;
        if (record.dev_id === 2) return <LaptopOutlined />;
        return null;
    }
}

];
export default function Dashboard(){
    // dataQurban需自行通过useState/接口请求获取后传入
    return (
        <Table columns={columns} dataSource={dataQurban} rowKey="id" />
    )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 18:00:53