# react-native: React Native 快速入门 URL: https://generaltranslation.com/zh/docs/react-native/tutorials/quickstart.mdx --- title: React Native 快速入门 description: 在 10 分钟内为你的 React Native 应用添加多种语言 --- 完成本指南后,你的 React Native 应用将能够以多种语言显示内容,并提供一个可供用户操作的语言切换器。 **前提条件:** * 一个使用 React Native CLI 创建的应用 (不包括 Expo;Expo 项目请参阅 [Expo 快速入门](/docs/react-native/tutorials/quickstart-expo)) * Node.js 18+ `gt-react-native` 仍处于实验阶段,可能并不适用于所有项目。 如果你遇到任何问题,请通过[在 GitHub 上提交 issue](https://github.com/generaltranslation/gt/issues)告知我们。 **想自动完成设置?** 运行 `npx gt@latest`,使用[设置向导](/docs/cli/init)完成全部配置。本指南介绍的是手动设置。 *** ## 第 1 步:安装软件包 `gt-react-native` 是为你的应用提供翻译能力的库。`gt` 是用于为生产环境准备翻译的 CLI 工具。 ```bash npm i gt-react-native npm i -D gt cd ios && pod install ``` ```bash yarn add gt-react-native yarn add --dev gt cd ios && pod install ``` ```bash bun add gt-react-native bun add --dev gt cd ios && pod install ``` ```bash pnpm add gt-react-native pnpm add --save-dev gt cd ios && pod install ``` *** ## 第 2 步:创建翻译配置文件 在项目根目录下创建一个 **`gt.config.json`** 文件,用于告诉该库你支持哪些语言: ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["es", "fr", "ja"], "files": { "gt": { "output": "content/[locale].json" } } } ``` * **`defaultLocale`** — 你的应用使用的语言 (即源语言) 。 * **`locales`** — 你要翻译到的语言。从[支持的区域设置列表](/docs/platform/supported-locales)中任选即可。 * **`files.gt.output`** — CLI 保存翻译文件的位置。`[locale]` 会替换为各语言代码 (例如 `content/es.json`) 。 *** ## 第 3 步:设置 polyfill React Native 的 JavaScript runtime 默认不包含 `gt-react-native` 所需的 `Intl` API。最简单的解决办法是使用随附的 Babel 插件。 将它添加到 Babel 配置中,并把 `entryPointFilePath` 指向应用的入口文件 (查看 `package.json` 中的 `"main"` 字段) : ```js title="babel.config.js" const path = require('path'); const gtPlugin = require('gt-react-native/plugin'); const gtConfig = require('./gt.config.json'); module.exports = { presets: ['module:@react-native/babel-preset'], plugins: [ [ gtPlugin, { locales: [gtConfig.defaultLocale, ...gtConfig.locales], entryPointFilePath: path.resolve(__dirname, 'App.tsx'), }, ], ], }; ``` 安装 FormatJS polyfill,并在入口文件顶部导入。你需要基础 polyfill,以及每种受支持语言对应的区域设置数据。 完整列表请参阅 [FormatJS 的 polyfill 文档](https://formatjs.github.io/docs/polyfills)。至少需要: ```tsx title="index.js" import '@formatjs/intl-getcanonicallocales/polyfill'; import '@formatjs/intl-locale/polyfill'; import '@formatjs/intl-pluralrules/polyfill-force'; import '@formatjs/intl-numberformat/polyfill'; import '@formatjs/intl-datetimeformat/polyfill'; import '@formatjs/intl-datetimeformat/add-all-tz'; // 为每种语言添加区域设置数据: import '@formatjs/intl-pluralrules/locale-data/en'; import '@formatjs/intl-pluralrules/locale-data/es'; import '@formatjs/intl-numberformat/locale-data/en'; import '@formatjs/intl-numberformat/locale-data/es'; // ... 对每个区域设置和 polyfill 重复添加 ``` *** ## 第 4 步:创建翻译加载器 Metro (React Native 的打包器) 不支持动态导入,因此你需要将每个区域设置明确映射到对应的翻译文件: ```ts title="loadTranslations.ts" const translations: Record = { es: require("./content/es.json"), fr: require("./content/fr.json"), ja: require("./content/ja.json"), }; export function loadTranslations(locale: string) { return translations[locale] ?? {}; } ``` 这些文件会在你运行 `npx gt translate` 时由 CLI 生成。 *** ## 第 5 步:将 GTProvider 添加到应用中 **`GTProvider`** 组件可让整个应用访问翻译内容。在根级包裹你的应用: ```tsx title="App.tsx" import { GTProvider } from 'gt-react-native'; import gtConfig from './gt.config.json'; import { loadTranslations } from './loadTranslations'; export default function App() { return ( {/* 您的应用内容 */} ); } ``` `GTProvider` 负责管理区域设置状态,并向所有子组件提供翻译功能。`devApiKey` prop 可在开发期间启用按需翻译。 *** ## 第 6 步:标记待翻译内容 使用 **``** 组件包裹任何需要翻译的文本: ```tsx title="screens/Home.tsx" import { Text, View } from 'react-native'; import { T } from 'gt-react-native'; export default function Home() { return ( Welcome to my app This content will be translated automatically. ); } ``` `` 中的所有内容都会作为一个整体进行翻译。 *** ## 第 7 步:添加语言切换器 使用 **`useLocaleSelector`** 钩子 构建语言选择器。与 `gt-react` 不同,`gt-react-native` 不提供预构建的 `` 组件——你需要使用这个 钩子 自行搭建 UI: ```tsx title="screens/Home.tsx" import { Text, View, Pressable } from 'react-native'; import { T, useLocaleSelector } from 'gt-react-native'; export default function Home() { const { locales, locale, setLocale } = useLocaleSelector(); return ( {locales.map((l) => ( setLocale(l)}> {l} ))} Welcome to my app ); } ``` `useLocaleSelector` 会返回可用的区域设置、当前区域设置以及一个设置函数,让你可以完全控制 UI。 *** ## 第 8 步:设置环境变量 (可选) 要在开发环境中看到翻译效果,你需要 General Translation 提供的 API 密钥。它们会启用**按需翻译**——这样你在开发过程中,应用就能实时翻译内容。 创建一个 **`.env`** 文件: ```bash title=".env" GT_API_KEY="your-api-key" GT_PROJECT_ID="your-project-id" ``` 前往 [dash.generaltranslation.com](https://dash.generaltranslation.com/signup) 免费获取你的密钥,或运行: ```bash npx gt auth ``` 在开发环境中,请使用以 `gtx-dev-` 开头的密钥。生产密钥 (`gtx-api-`) 仅限用于 CI/CD。 绝不要在应用包中暴露生产 API 密钥,也不要将其提交到版本控制系统。 可以。不使用 API 密钥时,`gt-react-native` 会作为标准 i18n 库运行。你将无法在开发环境中使用按需翻译,但仍然可以: * 手动提供自己的翻译文件 * 使用所有组件 (``、``、`LocaleSelector` 等) * 运行 `npx gt generate` 创建翻译文件模板,然后自行翻译 *** ## 第 9 步:查看运行效果 构建并运行你的应用: ```bash npx react-native run-ios # 或 npx react-native run-android ``` 使用语言选择器切换语言。你应该能看到内容已翻译成所选语言。 在开发环境中,会进行按需翻译——首次切换到新语言时,你可能会短暂看到加载状态。在生产环境中,翻译会预先生成,并且会立即加载。 *** ## 第 10 步:翻译字符串 (不只是 JSX) 对于普通字符串——例如 `placeholder` 属性或 `accessibilityLabel` 的值——请使用 **`useGT`** 钩子: ```tsx title="screens/Contact.tsx" import { TextInput, View } from 'react-native'; import { useGT } from 'gt-react-native'; export default function Contact() { const gt = useGT(); return ( ); } ``` *** ## 第 11 步:部署到生产环境 在生产环境中,翻译会在构建阶段预先生成 (不会发起实时 API 调用) 。将 `translate` 命令添加到构建脚本中: ```json title="package.json" { "scripts": { "build": "npx gt translate && " } } ``` 在 CI/CD 中设置 **生产环境** 环境变量: ```bash GT_PROJECT_ID=your-project-id GT_API_KEY=gtx-api-your-production-key ``` 生产密钥以 `gtx-api-` 开头 (不是 `gtx-dev-`) 。你可以从 [dash.generaltranslation.com](https://dash.generaltranslation.com) 获取。绝不要在应用程序包中暴露生产密钥。 就是这样——你的应用现在已经支持多语言了。🎉 *** ## 故障排查 ``` ERROR [Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'GtReactNative' could not be found.] ``` 这表示原生模块尚未正确链接。请运行 `cd ios && pod install`,然后重新构建应用。 ``` Error: You are using invalid locale codes in your configuration. ``` 这通常意味着 polyfill 未正确配置。请确认已配置 Babel 插件 (或已手动导入 polyfill) ,然后清除 Metro 缓存: ```bash npx react-native start --reset-cache ``` 这是正常现象。在开发环境中,会进行按需翻译 (你的内容会通过 API 实时翻译) 。**生产环境中不会有这种延迟**——所有翻译都会由 `npx gt translate` 预先生成。 含义不明确的文本可能会导致翻译不准确。例如,"apple" 既可能指水果,也可能指公司。添加 `context` prop 可帮助模型理解含义: ```jsx Apple ``` `` 和 `useGT()` 都支持 `context` 选项。 *** ## 下一步 * [**`` 组件指南**](/docs/react-native/guides/t) — 了解变量、复数形式和高级翻译模式 * [**字符串翻译指南**](/docs/react-native/guides/strings) — 深入学习 `useGT` * [**变量组件**](/docs/react-native/guides/variables) — 使用 ``、``、`` 和 `` 处理动态内容 * [**部署到生产环境**](/docs/react-native/tutorials/quickdeploy) — CI/CD 配置、缓存和性能优化