Types
DictionaryTranslationOptions
DictionaryTranslationOptions 类型的 API 参考
概述
DictionaryTranslationOptions
类型用于向字典条目传递变量并指定其渲染行为。
它与 useTranslations()
一起使用,向字典条目传递变量。
构建时翻译:
useTranslations()
翻译发生在构建时;但是,变量永远不会被翻译。
相反,它们会通过格式化插入到翻译中。
请确保遵循此处的部署指南。
参考
参数
Prop | Type | Default |
---|---|---|
variablesOptions?? | Record<string, Intl.NumberFormatOptions | Intl.DateTimeFormatOptions> | undefined |
variables?? | Record<string, any> | undefined |
描述
属性 | 描述 |
---|---|
variables | 一个对象,其键用于标识每个值在字典条目中的映射位置。 |
variablesOptions | 一个对象,其键用于标识变量,值用于定义变量的行为。更多信息请参见 Intl.NumberFormatOptions 和 Intl.DateTimeFormatOptions 。 |
示例
传递变量
为了向字典条目传递变量,我们需要做两件事:(1)向条目添加变量,(2)在 d()
调用中引用该变量。
首先,我们使用以下语法向字典条目添加变量:{username}
。
username
是变量的名称。
const dictionary = {
greeting: {
hello: 'Hello, {username}!',
},
};
export default dictionary;
接下来,我们引用该变量:
import { useTranslations } from 'gt-react';
const Component = () => {
const d = useTranslations();
return <div>{d('greeting.hello', { variables: { username : 'Brian123' } })}</div>;
};
添加变量选项
变量选项允许您自定义变量的渲染方式。
它使用与 variables
对象相同的语法。
const dictionary = {
account: {
balance: 'Your account balance: {account-balance}!',
},
};
export default dictionary;
接下来,我们引用该变量:
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
对象定义变量的行为。
下一步
- 查看字典了解更多关于字典和常见实践的信息。
- 查看
useTranslations()
了解更多关于字典接口的信息。 - 查看
Intl.NumberFormatOptions
和Intl.DateTimeFormatOptions
了解更多关于格式化选项的信息。
这份指南怎么样?