【问题标题】:How to use React-i18next with Table antd如何将 React-i18next 与 Table antd 一起使用
【发布时间】:2022-06-10 20:44:58
【问题描述】:

我使用antd 创建了以下表格组件:

import { Table } from "antd";

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

const columns = [
  {
    title: "Name",
    dataIndex: "name",
    key: "name"
  },
  {
    title: "Age",
    dataIndex: "age",
    key: "age"
  },
  {
    title: "Address",
    dataIndex: "address",
    key: "address"
  }
];

const CustomTable = () => {
  return (
    <>
      <Table dataSource={dataSource} columns={columns} />
    </>
  );
};

export default CustomTable;

现在我想为每个columns 名称添加翻译。我希望在React-i18next的帮助下获得此解决方案

使用这个库的一个简单例子是下面的代码:

const {t} = useTranslation();

t('textToTranslate');

此外,我还有一些 translate.json,我的翻译键和值在哪里,例如:

{
  "name": "name",
  "age": "age"
}

如何为每个 columns 添加翻译 -> name

【问题讨论】:

    标签: reactjs antd


    【解决方案1】:

    你可以改变生成列的方式,使用翻译作为典型的react prop:

    const dataSource = [
      {
        key: "1",
        name: "Mike",
        age: 32,
        address: "Downing Street"
      },
      {
        key: "2",
        name: "John",
        age: 42,
        address: "Downing Street"
      }
    ];
    
    const columns = [
      {
        title: "tableHeadings.name",
        dataIndex: "name",
        key: "name"
      },
      {
        title: "tableHeadings.age",
        dataIndex: "age",
        key: "age"
      },
      {
        title: "tableHeadings.address",
        dataIndex: "address",
        key: "address"
      }
    ];
    
    const CustomTable = () => {
      const { t } = useTranslation();
    
      return (
        <>
          <Table dataSource={dataSource}>
            {columns.map((column) => (
              <Table.Column
                key={column.key}
                title={t(column.title)}
                dataIndex={column.dataIndex}
              />
            ))}
          </Table>
        </>
      );
    };
    
    export default CustomTable;
    

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 1970-01-01
      • 2022-12-30
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 2020-10-19
      • 2018-01-11
      相关资源
      最近更新 更多