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

如何在antd Table中结合React-i18next实现列名国际化

核心问题在于useTranslation是React Hook,只能在函数组件或自定义Hook的顶层作用域调用,你当前把columns数组定义在组件外部,无法获取到翻译函数t,以下是两种可直接落地的实现方案:

方案1:组件内定义columns(最简单,适合单组件使用场景)

直接把columns配置移到CustomTable组件内部,调用useTranslation拿到t函数后,给每个列的title属性包裹t(翻译键)即可,完整代码如下:

import { Table } from "antd";
import { useTranslation } from "react-i18next";

const dataSource = [
  {
    key: "1",
    name: "Mike",
    age: 32,
    address: "Downing Street"
  },
  {
    key: "2",
    name: "John",
    age: 42,
    address: "Downing Street"
  }
];

const CustomTable = () => {
  const { t } = useTranslation();

  const columns = [
    {
      title: t("name"),
      dataIndex: "name",
      key: "name"
    },
    {
      title: t("age"),
      dataIndex: "age",
      key: "age"
    },
    {
      title: t("address"),
      dataIndex: "address",
      key: "address"
    }
  ];

  return <Table dataSource={dataSource} columns={columns} />;
};

export default CustomTable;

方案2:抽离columns工厂函数(适合多组件复用场景)

如果这套列配置需要在多个页面/组件里复用,可以把columns抽成一个接收t作为参数的函数,单独存为配置文件,避免重复写代码:

// /config/tableColumns.js 单独存放列配置
export const getUserTableColumns = (t) => [
  {
    title: t("name"),
    dataIndex: "name",
    key: "name"
  },
  {
    title: t("age"),
    dataIndex: "age",
    key: "age"
  },
  {
    title: t("address"),
    dataIndex: "address",
    key: "address"
  }
];

在组件中使用时传入t函数即可:

import { Table } from "antd";
import { useTranslation } from "react-i18next";
import { getUserTableColumns } from "./config/tableColumns";

const dataSource = [
  // 原有数据源代码无需修改
];

const CustomTable = () => {
  const { t } = useTranslation();
  const columns = getUserTableColumns(t);

  return <Table dataSource={dataSource} columns={columns} />;
};

export default CustomTable;

注意:你当前的翻译json文件里缺少address对应的键值对,记得补上对应各语言的翻译文案,切换语言时列名会自动跟随更新,不需要额外做刷新处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 23:36:37