# General Translation React SDKs (gt-react, gt-next, gt-react-native): React Native 快速入门
URL: https://generaltranslation.com/zh/docs/react/react-native-quickstart.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 使用 gt-react-native 为 React Native 应用添加自动国际化支持，涵盖 Expo 和原生 React Native CLI 两种方式。

`gt-react-native` 可为 React Native 应用添加自动国际化支持。你需要在应用的入口文件中初始化 General Translation，添加一个用于 React Native 所需 polyfill 的 Babel 插件，并用 [`GTProvider`](/docs/react/reference/components/gt-provider) 包裹应用。

本快速入门涵盖 Expo 和原生 React Native CLI 两种方式。对于 Web React 应用，请参阅 [React 快速入门](/docs/react/react-quickstart)。

<Callout type="warn">
  **警告：**`gt-react-native` 仍处于实验阶段，可能不适用于所有项目。它包含一个原生模块，因此 **不支持 Expo Go**——你需要使用开发构建。
</Callout>

## 快速入门 [#quickstart]

安装该软件包，创建配置文件，设置 polyfill，添加翻译加载器，通过 provider 初始化 General Translation，标记待翻译内容，并生成翻译。

### 1. 安装 `gt-react-native`

将 `gt-react-native` 安装为项目依赖，并将 [`gt` CLI](/docs/cli/quickstart) 安装为开发依赖。

<Tabs items={['npm', 'yarn', 'bun', 'pnpm']}>
  <Tab value="npm">
    ```bash
    npm install gt-react-native && npm install gt --save-dev
    ```
  </Tab>

  <Tab value="yarn">
    ```bash
    yarn add gt-react-native && yarn add --dev gt
    ```
  </Tab>

  <Tab value="bun">
    ```bash
    bun add gt-react-native && bun add --dev gt
    ```
  </Tab>

  <Tab value="pnpm">
    ```bash
    pnpm add gt-react-native && pnpm add --save-dev gt
    ```
  </Tab>
</Tabs>

<Callout type="info">
  **注意：** 如果你使用的是原生 React Native CLI，安装完成后请运行 `cd ios && pod install` 来链接原生模块。
</Callout>

### 2. 创建 `gt.config.json`

在项目根目录中创建一个 &#96;gt.config.json&#96;&#96; 文件。它用于声明源语言、目标区域设置，以及翻译文件的输出位置。

```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` 指向应用的入口文件。

<Tabs items={['Expo', 'React Native CLI']}>
  <Tab value="Expo">
    ```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'),
            },
          ],
        ],
      };
    };
    ```
  </Tab>

  <Tab value="React Native CLI">
    ```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'),
          },
        ],
      ],
    };
    ```
  </Tab>
</Tabs>

这个插件是一个 **具名导出**，因此要通过解构赋值获取它：`const { plugin: gtPlugin } = require('gt-react-native/plugin')`。它会在入口文件顶部注入所需的 `@formatjs` polyfill。如果 Metro 无法解析区域设置的区域数据，请按照[手动设置 polyfill](/docs/react/react-native/plugin#how-it-works)操作，并保持应用的区域设置不变。

### 4. 创建翻译加载器

Metro (React Native 的打包工具) 不支持动态导入，因此请通过静态 `require` 调用，将各个区域设置映射到对应的翻译文件。

```ts title="loadTranslations.ts"
const translations: Record<string, unknown> = {
  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`](/docs/cli/reference/commands/translate) 时，CLI 会生成这些文件。

<Callout type="warn">
  &#42;&#42;警告：&#42;&#42;这些文件在你创建之前并不存在，Metro 也不会在它们存在之前打包你的应用。请先运行 [`npx gt generate`](/docs/cli/reference/commands/generate) (无需 API 密钥) 或 [`npx gt translate`](/docs/cli/reference/commands/translate) (使用凭据) ，然后再启动应用。
</Callout>

### 5. 初始化 General Translation 并添加 provider

在应用的入口文件中，在渲染前调用一次 [`initializeGT`](/docs/react/reference/config#initialize)，然后用 [`GTProvider`](/docs/react/reference/components/gt-provider) 包裹应用。与 Web 包不同，[`GTProvider`](/docs/react/reference/components/gt-provider) 会在内部加载翻译，因此无需传入 `translations` prop，通常也不需要传入 `locale`——系统会自动检测。不过，如果你需要覆盖检测结果，仍然可以传入可选的 `locale` prop。

<Tabs items={['Expo', 'React Native CLI']}>
  <Tab value="Expo">
    ```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 (
        <GTProvider>
          <Slot />
        </GTProvider>
      );
    }
    ```
  </Tab>

  <Tab value="React Native CLI">
    ```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 (
        <GTProvider>
          <Home />
        </GTProvider>
      );
    }
    ```
  </Tab>
</Tabs>

<Callout type="info">
  **注意：**`projectId` 和 `devApiKey` 选项可在开发期间启用按需翻译。在 Expo 中，请使用 `EXPO_PUBLIC_` 前缀公开它们。
</Callout>

### 6. 标记要翻译的内容

将 JSX 包裹在 [`<T>`](/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 (
    <View>
      <View style={{ flexDirection: 'row', gap: 8 }}>
        {locales.map((l) => (
          <Pressable key={l} onPress={() => setLocale(l)}>
            <Text style={{ fontWeight: l === locale ? 'bold' : 'normal' }}>
              {l}
            </Text>
          </Pressable>
        ))}
      </View>
      <T>
        <Text>Welcome to my app</Text>
      </T>
      <TextInput accessibilityLabel={gt('Email input field')} />
    </View>
  );
}
```

[`useGT()`](/docs/react/reference/hooks/use-gt) 会直接返回翻译函数，因此请按以下方式调用：`const gt = useGT();`.

### 7. 生成翻译

运行 CLI，通过 General Translation API 为你的项目生成翻译。

```bash
npx gt translate
```

将此命令添加到构建脚本中，以确保 Production 构建始终使用最新的翻译：

```json title="package.json"
{
  "scripts": {
    "build": "npx gt translate && <your build command>"
  }
}
```

<Callout type="info">
  **注意：** [`npx gt translate`](/docs/cli/reference/commands/translate) 需要 project ID 和 production API 密钥，你需要在环境中将它们分别设置为 `GT_PROJECT_ID` 和 `GT_API_KEY`。运行 [`npx gt auth`](/docs/cli/reference/commands/auth)，或访问[仪表板](/docs/platform/dashboard/get-started)获取它们。
</Callout>

## Next steps

- /docs/react/guides/translating-jsx
- /docs/react/guides/translating-strings
- /docs/react/guides/managing-locales
- /docs/react/guides/formatting-variables

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
