# gt-next: General Translation Next.js SDK: tx
URL: https://generaltranslation.com/zh/docs/next/api/strings/tx.mdx
---
title: tx
description: 字符串翻译函数 tx 的 API 参考
---
## 概述
`tx` 函数是在服务端用于翻译字符串的函数。
```jsx
await tx('Hello, world!'); // 返回 'Hola, mundo!'
```
**运行时 翻译:**
`tx` 翻译会在 运行时 进行。
也就是说,翻译会实时完成,因此你可以翻译那些只有在 运行时 才能确定的内容。
## 参考
### 参数
| Name | Description |
| --------- | ------------------------------------------------------------------------------------------------------- |
| `content` | 需要翻译的字符串。 |
| `options` | 用于自定义 `tx` 行为的翻译选项。请参阅 [`RuntimeTranslationOptions`](/docs/next/api/types/runtime-translation-options)。 |
### 返回值
一个 Promise,会解析为包含翻译后内容的字符串;如果不需要翻译,则返回原始内容。
***
## 行为
`tx` 函数会在 运行时 翻译字符串。
这意味着翻译是在运行时实时完成的,因此你可以翻译只有到 运行时 才能确定的内容。
代价是,等待按需翻译加载时会产生延迟,速度也会明显更慢。
我们建议你尽可能使用 [`getGT`](/docs/next/api/strings/use-gt)、[`useGT`](/docs/next/api/strings/use-gt) 或 [``](/docs/next/api/components/t) 在构建时翻译所有内容,
仅在必要时才使用按需翻译,例如 `tx` 和 [``](/docs/next/api/components/tx)。
请务必遵循[这里的部署指南](/docs/next/tutorials/quickdeploy)。
***
## 示例
### 基本用法
你可以使用 `tx` 翻译字符串。
```javascript title="src/components/translateGreeting.jsx" copy
import { tx } from 'gt-next/server';
export default async function translateGreeting() {
return await tx("Hello, world!"); // [!code highlight]
}
```
### 添加 context
你可以通过提供翻译时要参考的 context 来自定义翻译。
```javascript title="TranslateWithOptions.jsx" copy
import { tx } from 'gt-next/server';
export default async function TranslateWithOptions() {
return await tx("Hello, world!", {
$context: 'Translate informally' // [!code highlight]
});
}
```
### 使用变量
要向字符串传入值,你必须:(1) 指定一个标识符,以及 (2) 在传入的对象中引用该标识符。
```jsx title="translateWithVariables.js" copy
// [!code word:price]
import { tx } from 'gt-next/server';
export default async function translateWithVariables() {
return await tx("The cost is {price, number, ::currency/USD}", {
price: 29.99,
});
}
```
### 指定区域设置
你可以指定用于翻译的区域设置。
默认情况下,区域设置为用户的首选语言。
```jsx title="translateWithLocale.js" copy
import { tx } from 'gt-next/server';
export default async function translateWithLocale() {
return await tx("Hello, world!", { $locale: 'fr' }); // [!code highlight]
}
```
***
## 说明
* `tx` 仅适用于服务端,不能在客户端组件中使用。
* 使用 `tx` 的翻译发生在 运行时,也就是说会在运行时即时翻译。这比在构建时完成翻译要慢得多。
## 后续步骤
* 请参阅 [`useGT`](/docs/next/api/strings/use-gt) 和 [`getGT`](/docs/next/api/strings/get-gt),了解如何在部署前翻译字符串。
* 如需翻译 JSX,请参阅 [``](/docs/next/api/components/t) 和 [``](/docs/next/api/components/tx)。
* 有关如何自定义翻译的更多信息,请参阅 [`RuntimeTranslationOptions`](/docs/next/api/types/runtime-translation-options)。