# General Translation React SDKs (gt-react, gt-next): React Native 快速入门
URL: https://generaltranslation.com/zh/docs/react/react-native-quickstart.mdx
---
title: React Native 快速入门
description: 使用 gt-react-native 为 React Native 应用添加自动国际化支持,涵盖 Expo 和原生 React Native CLI 两种方式。
related:
links:
- /docs/react/guides/translating-jsx
- /docs/react/guides/translating-strings
- /docs/react/guides/managing-locales
- /docs/react/guides/formatting-variables
---
`gt-react-native` 可为 React Native 应用添加自动国际化支持。你需要在应用的入口文件中初始化 General Translation,添加一个用于 React Native 所需 polyfill 的 Babel 插件,并用 `GTProvider` 包裹应用。
本快速入门涵盖 Expo 和原生 React Native CLI 两种方式。对于 Web React 应用,请参阅 [React 快速入门](/docs/react/react-quickstart)。
`gt-react-native` 仍处于实验阶段,可能不适用于所有项目。它包含一个原生模块,因此 **不支持 Expo Go**——你需要使用开发构建。
## 快速入门 [#quickstart]
安装该软件包,创建配置文件,设置 polyfill,添加翻译加载器,通过 provider 初始化 General Translation,标记待翻译内容,并生成翻译。
### 1. 安装 `gt-react-native`
将 `gt-react-native` 安装为项目依赖,并将 [`gt` CLI](/docs/cli/quickstart) 安装为开发依赖。
```bash
npm install gt-react-native && npm install gt --save-dev
```
```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
```
*注意:如果你使用的是原生 React Native CLI,安装完成后请运行 `cd ios && pod install` 来链接原生模块。*
### 2. 创建 `gt.config.json`
在项目根目录中创建一个 `gt.config.json`` 文件。它用于声明源语言、目标区域设置,以及翻译文件的输出位置。
```json title="gt.config.json"
{
"defaultLocale": "en",
"locales": ["es", "fr", "ja"],
"files": {
"gt": {
"output": "src/_gt/[locale].json"
}
}
}
```
* `defaultLocale` — 应用编写所使用的语言。
* `locales` — 要翻译到哪些语言。从[支持的区域设置](/docs/platform/dashboard/reference/supported-locales)中选择。
* `files.gt.output` — CLI 会将翻译文件写入的位置。`[locale]` 会被替换为各个区域设置代码。
### 3. 设置 polyfill
React Native 的 JavaScript 运行时不包含 `gt-react-native` 所需的 `Intl` API。添加随附的 Babel 插件,并将 `entryPointFilePath` 指向应用的入口文件。
```js title="babel.config.js"
const { plugin: 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'),
},
],
],
};
};
```
```js title="babel.config.js"
const path = require('path');
const { plugin: 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, 'index.js'),
},
],
],
};
```
这个插件是一个 **具名导出**,因此要通过解构赋值获取它:`const { plugin: gtPlugin } = require('gt-react-native/plugin')`。它会在入口文件顶部注入所需的 `@formatjs` polyfill。如果在你的设置中无法生效,请手动导入这些 polyfill——参见 [FormatJS 的 polyfill 文档](https://formatjs.github.io/docs/polyfills)。
### 4. 创建翻译加载器
Metro (React Native 的打包工具) 不支持动态导入,因此请通过静态 `require` 调用,将各个区域设置映射到对应的翻译文件。
```ts title="loadTranslations.ts"
const translations: Record = {
es: require('./src/_gt/es.json'),
fr: require('./src/_gt/fr.json'),
ja: require('./src/_gt/ja.json'),
};
export function loadTranslations(locale: string) {
return translations[locale] ?? {};
}
```
运行 `npx gt translate` 时,CLI 会生成这些文件。
### 5. 初始化 General Translation 并添加 provider
在应用的入口文件中,在渲染前调用一次 [`initializeGT`](/docs/node/reference/functions/initialize-gt),然后用 `GTProvider` 包裹应用。与 Web 包不同,`GTProvider` 会在内部加载翻译,因此无需传入 `translations` prop,通常也不需要传入 `locale`——系统会自动检测。不过,如果你需要覆盖检测结果,仍然可以传入可选的 `locale` prop。
```tsx title="app/_layout.tsx"
import { Slot } from 'expo-router';
import { GTProvider, initializeGT } from 'gt-react-native';
import gtConfig from '../gt.config.json';
import { loadTranslations } from '../loadTranslations';
// 只需初始化一次,在模块级别执行
initializeGT({
...gtConfig,
loadTranslations,
projectId: process.env.EXPO_PUBLIC_GT_PROJECT_ID,
devApiKey: process.env.EXPO_PUBLIC_GT_DEV_API_KEY,
});
export default function RootLayout() {
return (
);
}
```
```js title="index.js"
import { AppRegistry } from 'react-native';
import { initializeGT } from 'gt-react-native';
import App from './App';
import { name as appName } from './app.json';
import gtConfig from './gt.config.json';
import { loadTranslations } from './loadTranslations';
// 只需初始化一次,在注册应用之前执行
initializeGT({ ...gtConfig, loadTranslations });
AppRegistry.registerComponent(appName, () => App);
```
```tsx title="App.tsx"
import { GTProvider } from 'gt-react-native';
import Home from './src/Home';
export default function App() {
return (
);
}
```
*注意:`projectId` 和 `devApiKey` 选项可在开发期间启用按需翻译。在 Expo 中,请使用 `EXPO_PUBLIC_` 前缀公开它们。*
### 6. 标记要翻译的内容
将 JSX 包裹在 [``](/docs/react/reference/components/t) 组件中,以便进行原地翻译。对于 `placeholder` 和 `accessibilityLabel` 这类独立字符串的值,请使用 [`useGT`](/docs/react/reference/hooks/use-gt) 钩子。要构建语言切换器,请使用 [`useLocaleSelector`](/docs/react/reference/hooks/use-locale-selector) 钩子——`gt-react-native` 不提供预构建的选择器组件。
```tsx title="src/Home.tsx"
import { Text, View, Pressable, TextInput } from 'react-native';
import { T, useGT, useLocaleSelector } from 'gt-react-native';
export default function Home() {
const gt = useGT();
const { locales, locale, setLocale } = useLocaleSelector();
return (
{locales.map((l) => (
setLocale(l)}>
{l}
))}
Welcome to my app
);
}
```
`useGT()` 会直接返回翻译函数,因此请按以下方式调用:`const gt = useGT();`.
### 7. 生成翻译
运行 CLI,通过 General Translation API 为你的项目生成翻译。
```bash
npx gt translate
```
将此命令添加到构建脚本中,以确保 Production 构建始终使用最新的翻译:
```json title="package.json"
{
"scripts": {
"build": "npx gt translate && "
}
}
```
*注意:`npx gt translate` 需要 Project ID 和 production API key,你需要在环境中将它们分别设置为 `GT_PROJECT_ID` 和 `GT_API_KEY`。运行 `npx gt auth`,或访问[仪表板](/docs/platform/dashboard/get-started)获取它们。*
## Next steps
- /docs/react/guides/translating-jsx
- /docs/react/guides/translating-strings
- /docs/react/guides/managing-locales
- /docs/react/guides/formatting-variables