Types

DictionaryTranslationOptions

DictionaryTranslationOptions 类型的 API 参考

概述

DictionaryTranslationOptions 类型用于向字典条目传递变量并指定其渲染行为。 它与 useTranslations() 一起使用,向字典条目传递变量。

构建时翻译: useTranslations() 翻译发生在构建时;但是,变量永远不会被翻译。 相反,它们会通过格式化插入到翻译中。 请确保遵循此处的部署指南

参考

参数

PropTypeDefault
variablesOptions??
Record<string, Intl.NumberFormatOptions | Intl.DateTimeFormatOptions>
undefined
variables??
Record<string, any>
undefined

描述

属性描述
variables一个对象,其键用于标识每个值在字典条目中的映射位置。
variablesOptions一个对象,其键用于标识变量,值用于定义变量的行为。更多信息请参见 Intl.NumberFormatOptionsIntl.DateTimeFormatOptions

示例

传递变量

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

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

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

export default dictionary;

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

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

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

添加变量选项

变量选项允许您自定义变量的渲染方式。 它使用与 variables 对象相同的语法。

dictionary.ts
const dictionary = {
  account: {
    balance: 'Your account balance: {account-balance}!',
  },
};

export default dictionary;

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

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

const Component = () => {
  const d = useTranslations();
  return <div>
    { d(
      'account.balance',
      {
        variables: { "account-balance" : 1000000 },
        variableOptions: { "account-balance": { style: 'currency', currency: 'USD' } }
      }
    ) }
  </div>;
};

注意事项

  • variables 对象将值传递给字典条目。
  • variablesOptions 对象定义变量的行为。

下一步

这份指南怎么样?