# General Translation React SDKs (gt-react, gt-next): useGT URL: https://generaltranslation.com/zh/docs/react/reference/hooks/use-gt.mdx --- title: useGT description: 获取一个函数,以便使用 General Translation gt-react 内联翻译字符串。useGT 的 API 参考。 --- `useGT` 钩子会返回一个函数,用于将字符串翻译为当前区域设置。可用于标签、占位符以及其他不适合使用 [``](/docs/react/reference/components/t) 的独立字符串。 *可用于 `gt-react`、`gt-next`、`gt-tanstack-start` 和 `gt-react-native`。示例从 `gt-react` 导入;请改为从你所用框架对应的包中导入。* ## 概览 [#overview] 调用 `useGT` 获取翻译函数,然后向其传入一个字符串。它会直接返回该函数。 ```tsx const gt = useGT();

{gt('This text will be translated')}

; ``` *注意:在 `gt-react` 中,请在 [``](/docs/react/reference/components/gt-provider) 内调用 `useGT`。在 `gt-next` 中,它也可用于同步服务器组件。请写成 `const gt = useGT()`——该钩子会直接返回函数,而不是对象。* ## 工作原理 [#how-it-works] * **构建时翻译。** 在生产环境中,传给 `gt` 的字符串会在部署前的构建阶段完成翻译。只有在构建时已知的内容才能被翻译。缺少翻译时,会回退到原始字符串。 * **开发环境中按需翻译。** 使用开发 API 密钥时,`gt` 会按需翻译,方便你预览不同区域设置,但会有轻微延迟;这种延迟在生产环境中不会出现。 * **变量不会被翻译。** 插值值会插入到翻译后的字符串中,但其本身绝不会被翻译。 ## 参数 [#parameters] `useGT` 不接收任何参数。 ## 返回值 [#returns] **类型** `(content: string, options?: InlineTranslationOptions) => string` 一个函数,用于将提供的字符串翻译为当前生效的区域设置。 | 名称 | 描述 | 类型 | 可选 | | --------- | -------------------------------------------- | ------------------------------------------------------------------------------------ | -- | | `content` | 要翻译的字符串内容。 | `string` | 否 | | `options` | 插值变量以及诸如 `$context`、`$id` 和 `$maxChars` 的选项。 | [`InlineTranslationOptions`](/docs/react/reference/types/inline-translation-options) | 是 | ## 示例 [#examples] ```tsx import { useGT } from 'gt-react'; export default function TranslateGreeting() { const gt = useGT(); return

{gt('Hello, Alice!')}

; } // "Hello, Alice!" 会被翻译成用户所在区域设置对应的语言。 ``` ```tsx import { useGT } from 'gt-react'; export default function TranslateGreeting() { const gt = useGT(); return

{gt('Hello, {name}!', { name: 'Alice' })}

; } // "Alice" 是变量,不会被翻译。 ``` ```tsx import { useGT } from 'gt-react'; export default function ItemCount() { const gt = useGT(); return (

{gt( 'There are {count, plural, =0 {no items} =1 {one item} other {{count} items}} in the cart', { count: 10 } )}

); } ``` `gt-react` 支持使用 [ICU message format](https://unicode-org.github.io/icu/userguide/format_parse/messages/) 对变量进行格式化。 ## 注意事项 [#notes] * `useGT` 用于翻译字符串;翻译会在构建时完成 (开发时也可按需进行) 。 * 在异步 App Router 组件中,请改用 [`getGT`](/docs/react/nextjs/reference/functions/get-gt)。 * 如果要基于字典按 id 查找,请使用 [`useTranslations`](/docs/react/reference/hooks/use-translations);如果要在模块作用域注册字符串,请将 [`msg`](/docs/react/reference/functions/msg) 与 [`useMessages`](/docs/react/reference/hooks/use-messages) 搭配使用。