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

如何在TanStack Table列中渲染JSX元素?

在TanStack React Table中渲染JSX元素

你用accessorFn返回JSX导致浏览器显示对象,核心原因是**accessorFn/accessorKey的作用是提取数据值,而非负责UI渲染**。要在表格列中渲染自定义JSX,应该使用列配置中的cell渲染函数。

修正后的代码示例

interface RetailPriceTableColumnDef {
    commodity: string;
    country: string;
    price: number;
    date: string;
    emoji: string;
}

const columns: ColumnDef<RetailPriceTableColumnDef>[] = [
    {
        accessorKey: 'commodity',
        header: 'Commodity',
    },
    {
        header: 'Country',
        // 如需排序/过滤,保留accessorKey提取原始数据值
        accessorKey: 'country',
        // 使用cell函数渲染自定义JSX
        cell: ({ row }) => {
            return <CountryWithEmoji emoji={row.original.emoji} name={row.original.country} />;
        },
    },
    {
        accessorKey: 'price',
        header: 'Retail Price ($Kg)',
    },
    {
        accessorKey: 'date',
        header: 'Last Updated',
    },
];

export const RetailPricesTable = () => {
    const { data, error, loading } = useQuery(LatestRetailPricesDocument, {
        variables: {
            groupId: 1,
            commodityIds: 1,
        },
    });
    return <div>{data && <DataTable columns={columns} data={data?.latestRetailPrices} />}</div>;
};

关键说明

  • 如果不需要对该列做排序、过滤等操作,可以直接省略accessorKey/accessorFn,仅用cell函数完成渲染。
  • cell函数参数中的row.original可直接获取当前行的原始数据,方便传递给自定义组件。
  • 若要基于该列数据排序,accessorKey/accessorFn必须返回可用于比较的原始值(比如这里的row.country),不能返回JSX。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 13:52:13