Types

DictionaryTranslationOptions

DictionaryTranslationOptions 类型 API 参考

概览

DictionaryTranslationOptions 类型用于向字典条目传入变量,并指定其渲染行为。 它与 useTranslationsgetTranslations 搭配使用,以向字典条目传递变量。

构建时翻译: 使用 useTranslationsgetTranslations 时,不会对变量进行翻译,只有原始字符串会被翻译。 如需翻译包含动态内容的字符串,请参阅 tx

参考资料

参数

Prop

Type

描述

Prop描述
variables一个对象,其中的键用于标识每个 value 在字典 Entry 中的映射位置。

示例

传递变量

要向字典条目传入变量,我们需要做两件事:(1) 在该条目中添加一个变量,(2) 在 d 调用中引用该变量。

首先,使用如下语法向字典条目添加变量:{username}username 是该变量的名称。

dictionary.ts
const dictionary = {
  greeting: {
    hello: '您好,{username}!',
  },
};

export default dictionary;

接下来,我们引用该变量:

Component.tsx
import { useTranslations } from 'gt-next';

const Component = () => {
  const d = useTranslations();
  return <div>{d('greeting.hello', { username : 'Brian123' })}</div>;
};

使用 ICU 消息格式

gt-next 支持 ICU 消息格式,可用于格式化变量。

dictionary.ts
const dictionary = {
  account: {
    balance: '您的账户余额为:{dollars, number, ::currency/USD}',
  },
};

export default dictionary;

接下来,我们引用这个变量:

Component.tsx
import { useTranslations } from 'gt-next';

const Component = () => {
  const d = useTranslations();
  return <div>
    { d(
      'account.balance',
      {
        "dollars" : 1000000,
      }
    ) }
  </div>;
};

备注

  • variables 对象会将值传递给字典中的 Entry。
  • variablesOptions 对象用于定义变量的行为。

后续步骤

本指南如何?

DictionaryTranslationOptions