# gt-next: General Translation Next.js SDK: 翻译字符串 URL: https://generaltranslation.com/zh/docs/next/tutorials/translating-strings.mdx --- title: 翻译字符串 description: 如何翻译字符串 --- ## 概览 本指南将逐步讲解如何在你的 Next.js 应用中使用 [`useGT`](/docs/next/api/strings/use-gt)、[`getGT`](/docs/next/api/strings/get-gt) 和 [`tx`](/docs/next/api/strings/tx) 翻译字符串。 ## 前提条件 我们假定你已在项目中安装 `gt-next`,并且已经按照或正在参考[快速入门指南](/docs/next)进行设置。 ## 翻译字符串 ### 客户端组件 处理任何客户端字符串时,请使用 [`useGT`](/docs/next/api/strings/use-gt)。 请注意,`useGT` 必须在 [``](/docs/next/api/components/gtprovider) 的子组件内调用。 ```jsx title="src/components/MyComponent.jsx" copy import { useGT } from 'gt-next'; export default function MyComponent() { const gt = useGT(); // [!code highlight] return (

{gt('This is a string that gets translated')}

// [!code highlight]
); } ``` ### 服务器端组件 对于所有服务器端字符串,请使用 [`getGT`](/docs/next/api/strings/get-gt)。 ```jsx title="src/pages/index.jsx" copy import { getGT } from 'gt-next/server'; export default async function Home() { const gt = await getGT(); // [!code highlight] return (

{gt('This is a string that gets translated')}

// [!code highlight]
); } ``` **注意:** 在开发环境中,如果你在 runtime 进行内容翻译,则需要刷新页面,才能看到通过 [`getGT`](/docs/next/api/strings/get-gt) 获取的字符串的翻译结果。 **生产环境中不会出现这种情况。** ### 添加变量 变量是可能发生变化、但不会被翻译的值。 要在字符串中添加变量,请使用以下模式: ```jsx title="MyComponent.jsx" copy import { useGT } from 'gt-next'; export default function MyComponent() { const gt = useGT(); return (

{gt('Hello there, {username}', { variables: { username: 'Brian123' }})}

// [!code highlight]
); } ``` 这对 [`useGT`](/docs/next/api/strings/use-gt) 和 [`getGT`](/docs/next/api/strings/get-gt) 都适用。 ### 动态内容 假设你有一个会变化的字符串。 你可以使用 [`tx`](/docs/next/api/strings/tx) 函数在 runtime 时对该字符串进行翻译。 ```jsx title="MyComponent.jsx" copy import { tx } from 'gt-next/server'; export default async function MyComponent({ username }) { const translation = await tx(`Hello, ${username}. How is your day?`); // [!code highlight] return (

{translation}

// [!code highlight]
); } ``` **注意:** [`tx`](/docs/next/api/strings/tx) 函数仅在服务器端可用,且只应在确有必要时使用。 runtime 翻译通常会带来延迟。 请尽可能使用 [`getGT`](/docs/next/api/strings/get-gt) 或 [`useGT`](/docs/next/api/strings/use-gt) 在部署前完成翻译。 *** ## 注意事项 * 翻译字符串时,请使用 [`useGT`](/docs/next/api/strings/use-gt)、[`getGT`](/docs/next/api/strings/get-gt) 和 [`tx`](/docs/next/api/strings/tx)。 * `useGT` 和 `getGT` 会在部署前完成翻译,而 `tx` 会在 runtime 进行翻译。请尽量少用 `tx`。 * 可以通过 `{ variables: { key: value } }` 模式向字符串中添加变量。 ## 后续步骤 * 返回[快速入门指南](/docs/next),完成项目的翻译配置。 * 查看 [`useGT`](/docs/next/api/strings/use-gt)、[`getGT`](/docs/next/api/strings/get-gt) 和 [`tx`](/docs/next/api/strings/tx) 的 API 参考文档。