# General Translation React SDKs (gt-react, gt-next): 使用字典进行翻译 URL: https://generaltranslation.com/zh/docs/react/guides/translating-with-dictionaries.mdx --- title: 使用字典进行翻译 description: 如何在 React、Next.js、TanStack Start 和 React Native 中,通过 General Translation 的 useTranslations 钩子从中央字典翻译字符串。 related: links: - /docs/react/guides/translating-strings - /docs/react/guides/translating-jsx - /docs/react/guides/handling-plurals-and-branches - /docs/react/guides/formatting-variables --- 字典会将可翻译字符串集中存放在一个地方,通过 id 作为键来组织,而不是直接内联在组件中。这适合偏好集中管理文案的团队,或正在从基于键的 i18n 库迁移的团队。对大多数应用来说,改用 [``](/docs/react/guides/translating-jsx) 和 [`useGT`](/docs/react/guides/translating-strings) 即可。 ## 提供字典 [#provide] 如何注册各区域设置的字典,取决于你所使用的框架。 通过 `dictionaries` prop 将字典传给 `GTProvider`,并同时传入必需的 `locale` 和 `translations`。 ```tsx ; ``` 在 Next.js 中,你无需将字典传给 `GTProvider`。请在项目根目录创建一个字典文件,并通过配置插件注册它,或者让系统自动检测。 ```json title="dictionary.json" { "home": { "title": "Welcome back" } } ``` ```ts title="next.config.ts" import { withGTConfig } from 'gt-next/config'; export default withGTConfig(nextConfig, { dictionary: './dictionary.json' }); ``` 通过 `dictionaries` prop 将字典传给 `GTProvider`,并同时传入必需的 `locale` 和 `translations`。 ```tsx ; ``` 通过 `dictionaries` prop 将字典传给 `GTProvider`,并同时传入当前的 `locale`。 ```tsx ; ``` ## 使用 `useTranslations` 查找条目 [#use-translations] 调用 [`useTranslations`](/docs/react/reference/hooks/use-translations) 获取查找函数,然后传入条目 id。使用选项对象进行插值。 ```tsx import { useTranslations } from 'gt-react'; function Greeting() { const t = useTranslations(); return

{t('home.title')}

; } ```
```tsx title="同步组件" import { useTranslations } from 'gt-next'; function Greeting() { const t = useTranslations(); return

{t('home.title')}

; } ``` ```tsx title="异步 App Router 组件" import { getTranslations } from 'gt-next/server'; async function Greeting() { const t = await getTranslations(); return

{t('home.title')}

; } ```
```tsx import { useTranslations } from 'gt-tanstack-start'; function Greeting() { const t = useTranslations(); return

{t('home.title')}

; } ```
```tsx import { useTranslations } from 'gt-react-native'; function Greeting() { const t = useTranslations(); return {t('home.title')}; } ```
传入根 id,即可将所有查找都限定在该 prefix 下。这在所有框架中的用法都相同 (在 Next.js 服务器端则使用 `getTranslations('home')`) : ```tsx const t = useTranslations('home'); t('title'); // 解析为 home.title ``` *注意:查找字典中不存在的 id 会抛出错误,因此请保持 id 与字典条目同步。* ## 读取嵌套对象 [#objects] 使用 `.obj(id)` 读取嵌套的条目组——例如,对一组标签进行遍历。 ```tsx const t = useTranslations(); const labels = t.obj('nav.links'); ``` ## Next steps - /docs/react/guides/translating-strings - /docs/react/guides/translating-jsx - /docs/react/guides/handling-plurals-and-branches - /docs/react/guides/formatting-variables