# react-native: 使用 Expo 的 React Native 快速入门 URL: https://generaltranslation.com/zh/docs/react-native/tutorials/quickstart-expo.mdx --- title: 使用 Expo 的 React Native 快速入门 description: 在 10 分钟内为你的 Expo 应用添加多语言支持 --- 完成本指南后,你的 Expo 应用将能够以多种语言显示内容,并提供一个用户可操作的语言切换器。 **前提条件:** * 一个 Expo 项目 (SDK 49+) * Node.js 18+ `gt-react-native` 仍处于实验阶段,可能无法在所有项目中正常运行。 如果你遇到任何问题,请通过[在 GitHub 上提交 issue](https://github.com/generaltranslation/gt/issues)告诉我们。 **想自动完成设置?** 运行 `npx gt@latest`,即可通过[设置向导](/docs/cli/init)完成全部配置。本指南介绍的是手动设置。 在找原生 React Native CLI 项目?请参阅 [React Native 快速入门](/docs/react-native/tutorials/quickstart)。 *** ## 第 1 步:安装软件包 `gt-react-native` 是为你的应用提供翻译能力的库。`gt` 是用于为生产环境准备翻译的 CLI 工具。 ```bash npm i gt-react-native npm i -D gt ``` ```bash yarn add gt-react-native yarn add --dev gt ``` ```bash bun add gt-react-native bun add --dev gt ``` ```bash pnpm add gt-react-native pnpm add --save-dev gt ``` *** ## 第 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 配置中: ```js title="babel.config.js" const gtPlugin = require('gt-react-native/plugin'); const gtConfig = require('./gt.config.json'); module.exports = function (api) { api.cache(true); return { presets: ['babel-preset-expo'], plugins: [ [ gtPlugin, { locales: [gtConfig.defaultLocale, ...gtConfig.locales], entryPointFilePath: require.resolve('expo-router/entry'), }, ], ], }; }; ``` 安装 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 (Expo 的打包器) 不支持动态导入,因此你需要将每个区域设置明确映射到对应的翻译文件: ```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/_layout.tsx" import { Slot } from 'expo-router'; import { GTProvider } from 'gt-react-native'; import gtConfig from '../gt.config.json'; import { loadTranslations } from '../loadTranslations'; export default function RootLayout() { return ( ); } ``` `GTProvider` 管理区域设置状态,并为所有子组件提供翻译功能。`devApiKey` prop 可在开发期间启用按需翻译。 *** ## 第 6 步:标记要翻译的内容 用 **``** 组件包裹你想翻译的文本: ```tsx title="app/index.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="app/index.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.local`** 文件。Expo 要求公开的环境变量以 `EXPO_PUBLIC_` 为前缀: ```bash title=".env.local" EXPO_PUBLIC_GT_DEV_API_KEY="your-dev-api-key" EXPO_PUBLIC_GT_PROJECT_ID="your-project-id" ``` 前往 [dash.generaltranslation.com](https://dash.generaltranslation.com/signup) 免费获取密钥,或运行: ```bash npx gt auth ``` 在开发环境中,请使用以 `gtx-dev-` 开头的密钥。生产密钥 (`gtx-api-`) 仅限用于 CI/CD。 切勿在应用 bundle 中暴露生产 API 密钥,也不要将其提交到源代码管理系统。 可以。不使用 API 密钥时,`gt-react-native` 会作为标准的 i18n 库运行。你将无法在开发环境中使用按需翻译,但仍然可以: * 手动提供自己的翻译文件 * 使用所有组件 (``、``、`LocaleSelector` 等) * 运行 `npx gt generate` 生成翻译文件模板,然后自行翻译 *** ## 第 9 步:查看运行效果 启动开发构建: ```bash npx expo start --dev-client ``` **Expo Go 不支持** `gt-react-native`,因为它包含原生模块。你需要使用[开发构建](https://docs.expo.dev/develop/development-builds/introduction/): ```bash npx expo run:ios # 或 npx expo run:android ``` 使用语言选择器切换语言。你应该会看到内容已被翻译。 在开发环境中,翻译是按需进行的——首次切换到某种新语言时,你可能会看到短暂的加载状态。在生产环境中,翻译会预先生成并立即加载。 *** ## 第 10 步:翻译字符串 (不仅限于 JSX) 对于普通字符串 (例如 `placeholder` 属性或 `accessibilityLabel` 的值) ,请使用 **`useGT`** 钩子: ```tsx title="app/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 中设置 **生产环境** 变量 (这些变量仅限服务端使用,不是 `EXPO_PUBLIC_`) : ```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) 获取。切勿在应用 bundle 中暴露生产密钥。 就是这样——你的应用现已支持多语言。🎉 *** ## 故障排查 ``` ERROR [Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'GtReactNative' could not be found.] ``` 这表示原生模块尚未链接。常见原因如下: 1. **你使用的是 Expo Go**,而不是开发构建。请切换到开发构建: ```bash npx expo run:ios # 或 npx expo run:android ``` 2. **Pods 依赖未更新 (iOS) 。** 请尝试重新安装: ```bash cd ios && rm -rf build Pods Podfile.lock && pod install && cd .. ``` ``` Error: You are using invalid locale codes in your configuration. ``` 这通常表示 polyfill 没有正确配置。请确认已配置 Babel 插件 (或已导入手动 polyfill) ,然后清除缓存: ```bash npx expo start --clear ``` 这是预期行为。在开发环境中,翻译是按需执行的 (你的内容会通过 API 实时翻译) 。**生产环境中不会有这种延迟**——所有翻译都会由 `npx gt translate` 预先生成。 有歧义的文本可能导致翻译不准确。例如,“apple” 既可能指水果,也可能指公司。可添加 `context` 属性来帮助区分: ```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 设置、缓存和性能优化