# react-native: 字典 URL: https://generaltranslation.com/zh/docs/react-native/guides/dictionaries.mdx --- title: 字典 description: 如何使用传统的基于字典的翻译模式 --- {/* 自动生成:请勿直接编辑。请改为编辑 content/docs-templates/ 中的模板。 */} 字典通过在嵌套对象中使用键值对来组织翻译,是一种传统的翻译管理方式。虽然推荐使用 [`` 组件](/docs/react-native/guides/t),但在从其他 i18n 库迁移时,或当你更希望集中管理翻译内容时,字典仍然很实用。 **建议:** 对于新项目,请使用 [`` 组件](/docs/react-native/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-native/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-native/api/dictionary/use-translations) 钩子可让你访问字典条目: ```tsx import { useTranslations } from 'gt-react-native'; 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-native/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-native/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-native/api/config/load-translations);如果要迁移现有翻译文件,请使用 [`loadDictionary`](/docs/react-native/api/config/load-dictionary)。 ## 生产环境配置 ### 构建流程 将翻译集成到构建流程中: ```json title="package.json" { "scripts": { "build": "npx gt translate && <...YOUR_BUILD_COMMAND...>" } } ``` ### 开发环境与生产环境下的行为 * **开发环境**:使用开发 API 密钥按需翻译词典条目 * **生产环境**:所有词典翻译都会在构建阶段预先生成 ## 结合组件使用 字典和 [`` 组件](/docs/react-native/guides/t) 可以配合使用: ```tsx function MixedApproach() { const t = useTranslations(); return (
{/* 字典用于简单字符串 */}

{t('page.title')}

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

This is a complex message with links.

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