【笔记】React 国际化

React 国际化

前言

仅管市面上存在多款流行的国际化解决方案,但是笔者个人精力有限在此只记录工作学习中遇到的解决方案(持续更新)

react-i18next 方案

1. 安装

pnpm install react-i18next i18next --save

2. 创建文件

src 目录下新建 locales ,并创建 en-US.jsonzh-CN.jsonresources.js

en-US.json

{
	"hello":"Hello"
}

zh-CN.json

{
	"hello":"你好"
}

resources.js

import enUS from './en_US.json';
import zh from './zh_CN.json';

const resources = {
  'en-US': {
    translation: enUS,
  },
  'zh-CN': {
    translation: zh,
  },
  zh: {
    translation: zh,
  },
};

export default resources;

src 下新建 i18n.ts

i18n.ts

import { initReactI18next } from 'react-i18next';
import i18n from 'i18next';
import resources from '@/locales/resources.js';
// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui)

let localLang = sessionStorage.getItem('lang');
const browserLang = navigator.language;
if (!localLang) {
  localLang = browserLang === 'zh-CN' ? 'zh-CN' : 'en-US';
}

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: localLang, // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources
    // you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage
    // if you're using a language detector, do not define the lng option

    interpolation: {
      escapeValue: false, // react already safes from xss
    },
  });

export default i18n;

3. 导入

main.ts/index.ts中全局导入 i18n.ts

main.ts & index.ts

import './index.less';
import App from './App';
import React from 'react';
import ReactDOM from 'react-dom';
import './i18n'  // 新增:导入i18n

ReactDOM.render(
  <React.StrictMode>
      <App />
  </React.StrictMode>,
  document.getElementById('root'),
);

4. 使用

在要使用国际化的页面使用useTranslation hook

Layout.tsx

import React from 'react';

// 顶部导入 useTranslation
import { useTranslation } from 'react-i18next';

const Layout: FC<any> = (props: PropsWithChildren<any>) => {
  
  // 组件内部使用hook
  const [t, i18n] = useTranslation();
  
  // 在事件方法中使用i18n.changeLanguage()方法
  const toggleI18n = () => {
    const locale = i18n.language === "zh-CN" ? "en-US" : "zh-CN";
    i18n.changeLanguage(locale)
  }

  return (
    <div>
      <button onClick={toggleI18n}> i18n切换 </button>
    </div>
  );
};

export default Layout;

5. 追加字典到现有语言项

如果依赖的第三方库已经绑定过选项字典,可以通过如下方法添加自己的字典到现有的语言项

创建字典的步骤和上述一致,但是在 main.ts 或者 index.ts 中的编写方式有所不同

// main.ts & index.ts
import { resources } from "@/locales/resources"
import { useTranslation } from "react-i18next"
// 省略其他代码...
const { i18n } = useTranslation();
Object.keys(resources).forEach((lan: string) => {
    i18n.addResourceBundle(lang, 'translation', localResources[lang], true, false);
})
posted @ 2025-03-18 23:14  世界尽头守望的勇者  阅读(133)  评论(0)    收藏  举报