Types

InlineTranslationOptions

InlineTranslationOptions 类型的 API 参考

概述

InlineTranslationOptions 类型用于将变量传递给内联翻译并指定其渲染行为。 您还可以为翻译添加上下文和标识符。 它与 useGT() 一起使用,以将变量传递给内联字符串翻译。

构建时翻译: useGT() 翻译发生在构建时;然而,变量从不被翻译。 相反,它们以格式化的方式插入到翻译中。 请确保遵循此处的部署指南

参考

参数

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

描述

Prop描述
context内容的上下文(用于翻译)。
id用于翻译编辑器的可选标识符。
variables一个对象,其中的键标识每个值在字符串中的映射位置。
variablesOptions一个对象,其中的键标识变量,值定义变量的行为。更多信息请参见 Intl.NumberFormatOptionsIntl.DateTimeFormatOptions

示例

上下文

为了给字符串添加上下文,我们使用 context 属性。

Component.tsx
import { useGT } from 'gt-react';
 
const Component = () => {
  const t = useGT();
  return <div>{t('Hello, world!', { context: 'a formal greeting' })}</div>;
};

传递变量

为了在字符串中添加变量,我们使用 {variable-name} 语法,其中大括号包裹变量名。

Component.tsx
import { useGT } from 'gt-react';
 
const Component = () => {
  const t = useGT();
  return <div>{t('Hello, {username}! How is your day?', { variables: { 'username' : 'Brian123' } })}</div>;
};

添加变量选项

您还可以使用 variablesOptions 属性自定义变量的呈现方式。

Component.tsx
import { useGT } from 'gt-react';
 
const Component = () => {
  const t = useGT();
  return <div>
    { t(
      'Your account balance: {account-balance}!',
      {
        variables: { "account-balance" : 1000000 },
        variableOptions: { "account-balance": { style: 'currency', currency: 'USD' } }
      }
    ) }
  </div>;
};

注意事项

  • InlineTranslationOptions 用于字符串翻译。
  • variables 对象将值传递给文本。
  • variablesOptions 对象定义变量的行为。

下一步

在本页面