# gt-react: General Translation React SDK: 字典 URL: https://generaltranslation.com/zh/docs/react/guides/dictionaries.mdx --- title: 字典 description: 如何使用传统的基于字典的翻译方式 --- {/* 自动生成:请勿直接编辑。请在 content/docs-templates/ 中编辑模板。 */} 字典通过嵌套对象中的键值对来组织翻译,这是较为传统的做法。虽然推荐使用 [`` 组件](/docs/react/guides/t),但在从其他 i18n 库迁移时,或当你更希望将翻译集中存储时,字典仍然很有用。 **建议:** 新项目请使用 [`` 组件](/docs/react/guides/t)。支持字典主要是为了迁移以及兼容现有的翻译工作流。 ## 字典式翻译与组件翻译 ### 字典模式 ```tsx // dictionary.ts export default { greetings: { hello: 'Hello, world!', welcome: 'Welcome, {name}!' } }; // 组件用法 function MyComponent() { const t = useTranslations(); return
{t('greetings.hello')}
; } ``` ### 组件方案 ```tsx // 直接使用组件 - 推荐 function MyComponent() { return
Hello, world!
; } ``` ## 取舍 ### 字典的优点 * **集中存储** - 所有翻译集中存放在一处 * **行业通用** - 与其他 i18n 库中的常见模式一致 * **迁移友好** - 便于迁移现有翻译 ### 字典方案的缺点 * **复杂性** - 需要更多的设置和配置 * **可维护性** - 内容与使用位置分离,更新起来更困难 * **可调试性** - 更难追踪翻译对应的是哪些组件 * **可读性** - 键名无法反映实际内容 ## 快速开始 ### 第 1 步:创建字典文件 在项目根目录或 `src` 目录下创建一个字典文件: ```ts title="dictionary.ts" const dictionary = { greetings: { hello: 'Hello, world!', welcome: 'Welcome to our app!' }, navigation: { home: 'Home', about: 'About', contact: 'Contact' } }; export default dictionary; ``` 或者使用 JSON 格式: ```json title="dictionary.json" { "greetings": { "hello": "Hello, world!", "welcome": "Welcome to our app!" }, "navigation": { "home": "Home", "about": "About", "contact": "Contact" } } ``` 然后将其传给你的 [``](/docs/react/api/components/gtprovider) 组件: ```jsx title="index.js" copy import dictionary from "./dictionary.js"; import config from "./gt.config.json"; createRoot(document.getElementById("root")!).render( {/* [!code highlight] */} ); ``` ### 第 2 步:在组件中使用 [`useTranslations`](/docs/react/api/dictionary/use-translations) 钩子 可让你访问字典条目: ```tsx import { useTranslations } from 'gt-react'; function MyComponent() { const t = useTranslations(); return (

{t('greetings.hello')}

{t('greetings.welcome')}

); } ``` ## 使用变量 使用 `{variable}` 语法在字典条目中添加变量: ```ts title="dictionary.ts" const dictionary = { user: { greeting: 'Hello, {name}!', itemCount: 'You have {count} items', orderTotal: 'Total: ${amount}' } }; ``` ```tsx function UserDashboard() { const t = useTranslations(); return (

{t('user.greeting', { name: 'Alice' })}

{t('user.itemCount', { count: 5 })}

{t('user.orderTotal', { amount: 99.99 })}

); } ``` ## 使用前缀 使用前缀可将字典的访问范围限定到特定部分: ```ts title="dictionary.ts" const dictionary = { dashboard: { header: { welcome: 'Welcome back!', lastLogin: 'Last login: {date}' }, stats: { totalUsers: 'Total Users: {count}', activeUsers: 'Active Users: {count}' } } }; ``` ```tsx function DashboardHeader() { // 前缀将访问范围限制在 'dashboard.header' const t = useTranslations('dashboard.header'); return (

{t('welcome')}

{/* -> dashboard.header.welcome */}

{t('lastLogin', { date: 'Today' })}

{/* -> dashboard.header.lastLogin */}
); } function DashboardStats() { // stats 部分使用不同的前缀 const t = useTranslations('dashboard.stats'); return (

{t('totalUsers', { count: 1000 })}

{/* -> dashboard.stats.totalUsers */}

{t('activeUsers', { count: 150 })}

{/* -> dashboard.stats.activeUsers */}
); } ``` ## 多语言支持 ### 自动翻译 (推荐) 大多数用户应使用 [`loadTranslations`](/docs/react/api/config/load-translations),根据基础字典自动生成翻译: ```ts title="dictionary.ts" const dictionary = { common: { save: 'Save', cancel: 'Cancel', delete: 'Delete' }, forms: { required: 'This field is required', email: 'Please enter a valid email' } }; export default dictionary; ``` 然后创建一个 `loadTranslations` 函数,用于加载生成的翻译文件: ```ts title="src/loadTranslations.ts" export default async function loadTranslations(locale: string) { const translations = await import(`./_gt/${locale}.json`); return translations.default; } ``` 将其传给 ``: ```tsx title="src/index.tsx" import loadTranslations from './loadTranslations'; import dictionary from './dictionary'; createRoot(document.getElementById("root")!).render( ); ``` GT 会根据你的基础字典,自动为其他语言生成翻译。运行 `npx gt translate`,即可为所有已配置的语言生成翻译。 ### 手动翻译文件 (迁移) 如果你是从其他 i18n 库迁移,或原本采用手动方式管理翻译,请使用 [`loadDictionary`](/docs/react/api/config/load-dictionary): ```ts title="src/loadDictionary.ts" export default async function loadDictionary(locale: string) { const translations = await import(`../public/locales/${locale}.json`); return translations.default; } ``` 这会从你的 `public/locales/` 目录中加载 JSON 翻译文件: **选择合适的方式:** 对于启用自动生成翻译的新项目,请使用 [`loadTranslations`](/docs/react/api/config/load-translations);如果要迁移现有的翻译文件,请使用 [`loadDictionary`](/docs/react/api/config/load-dictionary)。 ## 生产环境配置 ### 构建流程 将翻译集成到你的构建流程中: ```json title="package.json" { "scripts": { "build": "npx gt translate && <...YOUR_BUILD_COMMAND...>" } } ``` ### 开发环境与生产环境下的行为 * **Development**:使用开发 API 密钥按需翻译字典条目 * **生产环境**:所有字典翻译都会在构建步骤中预先生成 ## 与组件配合使用 字典和 [`` 组件](/docs/react/guides/t) 可以结合使用: ```tsx function MixedApproach() { const t = useTranslations(); return (
{/* 字典用于简单字符串 */}

{t('page.title')}

{/* T 组件用于复杂 JSX */}

This is a complex message with links.

{/* 字典用于表单标签 */}
); } ``` ## 后续步骤 **查看实际效果:**查看 [字典模式 示例应用](https://github.com/gt-examples/dictionary-pattern) 了解可运行的演示 — [在线预览](https://dictionary-pattern.generaltranslation.dev)。 * [语言指南](/docs/react/guides/languages) - 配置支持的语言和区域设置 * [动态内容指南](/docs/key-concepts/dynamic-content) - 处理 runtime 翻译需求 * API 参考: * [`useTranslations` 钩子](/docs/react/api/dictionary/use-translations)