',
optional: true,
default: 'undefined',
},
}}
/>
### 说明
| 属性 | 说明 |
| ----------- | ---------------------------------------------------------------- |
| `variables` | 一个对象,其中的键用于标识每个值在字符串中对应的位置。 |
| `$context` | 可选地在 `variables` 对象中加入 `$context` 变量,为内容提供上下文信息 (用于翻译) 。 |
| `$id` | 可选地在 `variables` 对象中加入 `$id` 变量,为翻译编辑器提供标识符。 |
| `$maxChars` | 可选地加入 `$maxChars` 变量,以限制翻译的字符数。该库会通过 `formatCutoff()` 逻辑严格执行此字符限制。 |
***
## 示例
### 上下文
为了给字符串添加上下文,我们使用 `$context` 属性。
```jsx title="Component.tsx"
// [!code word:$context]
import { useGT } from 'gt-react';
const Component = () => {
const gt = useGT();
return {gt('Hello, world!', { $context: 'a formal greeting' })}
;
};
```
### 传递变量
要在字符串中加入变量,可使用 `{variable-name}` 语法,即用花括号将变量名括起来。
```jsx title="Component.tsx"
// [!code word:username]
import { useGT } from 'gt-react';
const Component = () => {
const gt = useGT();
return {gt('Hello, {username}! How is your day?', { username: 'Brian123' })}
;
};
```
### 使用 ICU 消息格式
`gt-react` 支持 ICU 消息格式,因此你也可以格式化变量。
```jsx title="Component.tsx"
// [!code word:account-balance]
import { useGT } from 'gt-react';
const Component = () => {
const gt = useGT();
return
{ gt(
'Your account balance: {dollars, number, ::currency/USD}!',
{
"dollars" : 1000000,
}
) }
;
};
```
有关 ICU 消息格式的更多信息,请参阅 [ICU 消息格式文档](https://unicode-org.github.io/icu/userguide/format_parse/messages/)。
### 字符限制
使用 `$maxChars` 限制译文长度:
```jsx title="Component.tsx"
// [!code word:$maxChars]
import { useGT } from 'gt-react';
const Component = () => {
const gt = useGT();
return {gt('Welcome to our application', { $maxChars: 15 })}
;
// Output: "Bienvenue à no\u202F…"
};
```
***
## 说明
* `InlineTranslationOptions` 用于内联字符串翻译。
* `variables` 对象向文本传入值。
* `variablesOptions` 对象定义这些变量的行为。
## 后续步骤
* 有关内联字符串翻译的更多信息,请参阅 [`useGT`](/docs/react/api/strings/use-gt)。
* 有关格式选项的更多信息,请参阅 [`ICU 消息格式`](https://unicode-org.github.io/icu/userguide/format_parse/messages/)。