mcpField
R
react-i18next

react-i18next

github.com/yildizberkay开发2153 次安装36 周前更新
代码仓库

关于 react-i18next

react-i18next 是基于 i18next 的 React 国际化绑定,面向 React 和 React Native 开发者。它提供 Hook、HOC、渲染属性和组件等多种接入方式,并涵盖配置、SSR 与测试模式。

主要功能

  1. 01Hook、HOC 与渲染属性 API
  2. 02JSX 嵌入式翻译
  3. 03命名空间与懒加载
  4. 04插值、复数和上下文
  5. 05SSR 与 TypeScript 支持

适用场景

  1. 01为函数组件呈现翻译文本
  2. 02在 JSX 翻译中嵌入链接或组件
  3. 03按需加载多个翻译命名空间
  4. 04为服务端渲染传入初始翻译

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/yildizberkay/skills --skill react-i18next

安装后在 Claude Code 中输入/react-i18next确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
ssr.md
testing.md
trans-component.md

详细介绍

react-i18next 技能

react-i18next 是 React / React Native 的标准国际化框架,构建于 i18next 之上。本技能涵盖设置、配置、所有 API 接口和常见模式。

关键心智模型:i18next 是核心翻译引擎(配置、复数、插值、格式化)。react-i18next 是 React 绑定层,通过钩子、HOC、渲染属性和 Trans 组件将 i18next 连接到组件。

安装

npm install react-i18next i18next --save

# Common companion packages:
npm install i18next-http-backend i18next-browser-languagedetector --save

i18next 配置(i18n.js)

在入口点旁创建 i18n.js。它是 i18n 设置的唯一事实来源。

最简设置(内联资源)
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n
  .use(initReactI18next)
  .init({
    resources: {
      en: {
        translation: {
          "welcome": "Welcome to our app"
        }
      },
      tr: {
        translation: {
          "welcome": "Uygulamamıza hoş geldiniz"
        }
      }
    },
    lng: 'en',              // default language
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false     // React already escapes by default
    }
  });

export default i18n;
生产环境设置(使用后端 + 语言检测)
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

i18n
  .use(Backend)              // loads translations from /public/locales/{lng}/{ns}.json
  .use(LanguageDetector)     // detects user language
  .use(initReactI18next)     // binds i18next to React
  .init({
    fallbackLng: 'en',
    debug: true,             // set false in production
    interpolation: {
      escapeValue: false
    },
    // react-specific options (all optional):
    // react: {
    //   bindI18n: 'languageChanged',
    //   bindI18nStore: '',
    //   transEmptyNodeValue: '',
    //   transSupportBasicHtmlNodes: true,
    //   transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
    //   useSuspense: true,
    // }
  });

export default i18n;

然后在入口点导入:

import './i18n';  // must be imported before App
翻译文件结构

使用 i18next-http-backend 时,将文件放在:

public/
  locales/
    en/
      translation.json    ← default namespace
      common.json          ← additional namespace
    tr/
      translation.json
      common.json

核心 API

react-i18next 提供四种访问翻译的方式。请根据使用场景选择:

方法使用场景
useTranslation 钩子函数组件(推荐)
withTranslation HOC类组件或包装任意组件
Translation 渲染属性需要在任意组件类型中使用 t 函数
Trans 组件翻译包含嵌入式 HTML / 组件的 JSX 树
1. useTranslation 钩子(主要 API)
import { useTranslation } from 'react-i18next';

function MyComponent() {
  const { t, i18n } = useTranslation();
  return <h1>{t('welcome')}</h1>;
}

命名空间加载:

const { t } = useTranslation('common');           // single namespace
const { t } = useTranslation(['ns1', 'ns2']);      // multiple (first = default)
t('key');                                          // looks up in default ns
t('key', { ns: 'ns2' });                          // explicit namespace

keyPrefix(react-i18next >= 11.12.0,i18next >= 20.6.0):

// For deeply nested keys: { "very": { "deeply": { "nested": { "key": "value" }}}}
const { t } = useTranslation('translation', { keyPrefix: 'very.deeply.nested' });
t('key');  // → "value"

固定语言(react-i18next >= 12.3.1):

const { t } = useTranslation('translation', { lng: 'de' });

不使用 Suspense:

const { t, i18n, ready } = useTranslation('ns1', { useSuspense: false });
if (!ready) return <Loading />;  // must handle loading state yourself

Suspense 行为:默认情况下,useTranslation 会在加载翻译时触发 React Suspense。请将应用(或相关子树)包装在 <Suspense fallback="loading"> 中。

2. withTranslation HOC
import { withTranslation } from 'react-i18next';

function MyComponent({ t, i18n }) {
  return <p>{t('greeting')}</p>;
}
export default withTranslation()(MyComponent);           // default ns
export default withTranslation('common')(MyComponent);    // specific ns
export default withTranslation(['ns1', 'ns2'])(MyComponent); // multiple

不使用 Suspense:将 useSuspense={false} 作为属性传入,然后检查 props.tReady。

3. Translation 渲染属性
import { Translation } from 'react-i18next';

function MyComponent() {
  return (
    <Translation ns="common">
      {(t, { i18n }) => <p>{t('hello')}</p>}
    </Translation>
  );
}
4. Trans 组件

只有在需要在翻译字符串中嵌入 React 元素(链接、粗体文本、组件)时,才使用 Trans。普通文本请改用 t()。

import { Trans, useTranslation } from 'react-i18next';

function Welcome({ name, count }) {
  const { t } = useTranslation();
  return (
    <Trans i18nKey="userMessages" count={count}>
      Hello <strong title={t('nameTitle')}>{{name}}</strong>,
      you have {{count}} unread message.
      <Link to="/msgs">Go to messages</Link>.
    </Trans>
  );
}

翻译 JSON:

{
  "userMessages_one": "Hello <1>{{name}}</1>, you have {{count}} unread message. <5>Go to messages</5>.",
  "userMessages_other": "Hello <1>{{name}}</1>, you have {{count}} unread messages. <5>Go to messages</5>."
}

命名组件(v11.6.0+)——比索引标签更简洁:

<Trans
  i18nKey="myKey"
  defaults="hello <italic>beautiful</italic> <bold>{{what}}</bold>"
  values={{ what: 'world' }}
  components={{ italic: <i />, bold: <strong /> }}
/>

JSON:"myKey": "hello <italic>beautiful</italic> <bold>{{what}}</bold>"

简单 HTML 元素(v10.4.0+): 默认情况下,<br/>、<strong>、<i>、<p> 在翻译字符串中保持原样(由 transSupportBasicHtmlNodes 和 transKeepBasicHtmlNodesFor 选项控制)。

索引编号规则:Trans 的子元素按其在子元素数组中的位置编号。字符串和插值对象会获得索引,但不会被标签包裹。元素会使用 <N>...</N> 标签。

如需查看 Trans 组件属性和高级模式的完整参考,请阅读 references/trans-component.md。

常见模式

切换语言
function LanguageSwitcher() {
  const { i18n } = useTranslation();
  return (
    <select value={i18n.language} onChange={e => i18n.changeLanguage(e.target.value)}>
      <option value="en">English</option>
      <option value="tr">Türkçe</option>
    </select>
  );
}
在组件外使用 t()

直接导入已配置的 i18n 实例:

import i18n from './i18n';
i18n.t('my.key');
I18nextProvider(多个实例)

仅在支持多个 i18next 实例(例如组件库)或 SSR 时才需要:

import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';

<I18nextProvider i18n={i18n} defaultNS="translation">
  <App />
</I18nextProvider>
命名空间(多个翻译文件)

命名空间可将翻译拆分到单独的文件中并按需加载:

const { t } = useTranslation(['page1', 'common']);
t('key');                      // from 'page1' (first namespace)
t('key', { ns: 'common' });   // from 'common'

使用 useTranslation、withTranslation 或 Translation 的组件会自动进入 Suspense,直到所需的命名空间加载完成——无需预先加载所有翻译。

插值
{ "greeting": "Hello {{name}}, you are {{age}} years old" }
t('greeting', { name: 'Ali', age: 28 })
复数

i18next 使用类似 ICU 的复数后缀。对于英语:

{
  "item_one": "{{count}} item",
  "item_other": "{{count}} items"
}
t('item', { count: 5 })  // → "5 items"
上下文
{
  "friend_male": "A boyfriend",
  "friend_female": "A girlfriend"
}
t('friend', { context: 'male' })
嵌套
{
  "app": { "name": "MyApp" },
  "intro": "Welcome to $t(app.name)"
}

TypeScript 支持

需要 react-i18next >= 13.0.0 和 i18next >= 23.0.1。

请参阅官方指南 https://www.i18next.com/overview/typescript,了解如何设置类型安全的翻译。主要步骤如下:

  1. 创建资源类型定义文件
  2. 使用资源类型扩充 i18next 模块
  3. t 函数随后即可使用访问器语法:t($ => $.my.key)

SSR(Next.js、Remix、Gatsby)

  • Next.js(App Router):直接使用 i18next,并采用 App Router 模式 — 参见 references/ssr.md
  • Next.js(Pages Router):使用封装了 react-i18next 的 next-i18next
  • Remix:使用 remix-i18next
  • Gatsby:使用 gatsby-plugin-react-i18next

对于自定义 SSR,使用 useSSR hook 或 withSSR HOC,将初始翻译和语言从服务端传递到客户端:

import { useSSR } from 'react-i18next';
function InitSSR({ initialI18nStore, initialLanguage }) {
  useSSR(initialI18nStore, initialLanguage);
  return <App />;
}

如需了解更多详情,请阅读 references/ssr.md。

测试

以下是三种方式,从最简单到最全面:

1. 模拟 hook(Jest):

jest.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key) => key,
    i18n: { changeLanguage: () => new Promise(() => {}) },
  }),
  initReactI18next: { type: '3rdParty', init: () => {} },
}));

2. 导出原始组件 + 将 t 作为 prop 传入:

export { MyComponent };                              // for testing
export default withTranslation('ns')(MyComponent);   // for app
// In test: <MyComponent t={key => key} />

3. 在测试中完整配置 i18next(不进行模拟):

import i18n from 'i18next';
import { initReactI18next, I18nextProvider } from 'react-i18next';
i18n.use(initReactI18next).init({
  lng: 'en', fallbackLng: 'en',
  resources: { en: { translationsNS: {} } },
});
// Wrap component: <I18nextProvider i18n={i18n}><MyComponent /></I18nextProvider>

如需查看包含 spy 示例的详细测试指南,请阅读 references/testing.md。

React 选项参考

i18next.init({ react: { ... } }) 中的选项:

选项默认值说明
bindI18n'languageChanged'触发重新渲染的事件
bindI18nStore''触发重新渲染的存储事件
transEmptyNodeValue''Trans 中查询失败时使用的值
transSupportBasicHtmlNodestrue在翻译字符串中保留 <br/> 等标签
transKeepBasicHtmlNodesFor['br','strong','i','p']要保留的 HTML 标签
transWrapTextNodes''包装文本节点(例如,使用 'span' 修复 Google Translate 问题)
useSuspensetrue启用/禁用 Suspense
keyPrefixundefined为 useTranslation 的 t 函数自动添加前缀

参考文件

如需特定主题的详细文档,请阅读 references/ 目录中的以下文件:

  • references/trans-component.md — 完整的 Trans 组件 API、props、索引编号、命名组件、props 覆盖、列表、ICU 格式用法
  • references/testing.md — 使用 Jest mocks、spies 和完整 i18next 配置的详细测试模式
  • references/ssr.md — Next.js、Remix、Gatsby 的 SSR 模式,以及使用 useSSR/withSSR 的自定义 SSR

评论

支持 Markdown