前端国际化, React 项目多语言:React-i18next 本地化数据 && 请求后台数据

关键词:前端,国际化,多语言,react,react-i18next,i18n, antd

GitHub Examples

参考资料:

一、搭建 React 项目

npx create-react-app demo

二、安装 react-i18next

npm install i18next react-i18next --save

三、两种使用方式 (本地化数据、请求后台数据)

方式一:本地化数据

Basic sample:

import React from 'react';
import ReactDOM from 'react-dom';
import i18n from 'i18next';
import { useTranslation, initReactI18next } from 'react-i18next';

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    // the translations
    // (tip move them in a JSON file and import them)
    resources: {
      en: {
        translation: {
          'Welcome to React': 'Welcome to React and react-i18next'
        }
      },
      zh: {
        translation: {
          'Welcome to React': '欢迎使用 React 和 react-i18next'
        }
      }
    },
    lng: 'en',
    fallbackLng: 'en',

    interpolation: {
      escapeValue: false
    }
  });

function App() {
  const { t } = useTranslation();

  return <h2>{t('Welcome to React')}</h2>;
}

// append app to dom
ReactDOM.render(<App />, document.getElementById('root'));

Basic sample with JSON:

根据 resources 上面的注释,把 resources 部分提取到 json 文件中,然后 import 引入。

en.json:

{
  "translation": {
    "Welcome to React": "Welcome to React and react-i18next"
  }
}

zh.json:

{
  "translation": {
    "Welcome to React": "欢迎使用 React 和 react-i18next"
  }
}

注意:translation 是 react-i18next 默认的命名空间(暂时先记着这样写,后面可以自定义命名空间)

引入 JSON 文件:( 引入路径要根据 json 文件所在 src 目录下的相对路径 )

import React from 'react';
import ReactDOM from 'react-dom';
import i18n from 'i18next';
import en from './en.json';
import zh from './zh.json';
import { useTranslation, initReactI18next } from 'react-i18next';

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    // the translations
    // (tip move them in a JSON file and import them)
    resources: {
      en,
      zh
    },
    lng: 'en',
    fallbackLng: 'en',

    interpolation: {
      escapeValue: false
    }
  });

function App() {
  const { t } = useTranslation();

  return <h2>{t('Welcome to React')}</h2>;
}

// append app to dom
ReactDOM.render(<App />, document.getElementById('root'));

目前为止,还没有用到 i18next-xhr-backend , 这个插件可以使你的 json 文件放到 public 目录下使用(下例 Locales JSON)。

i18next-browser-languagedetector , 可以帮助你自动识别浏览器语言

Basic sample with Locales JSON: (推荐)

继续安装插件:

npm install i18next-xhr-backend i18next-browser-languagedetector --save

public 目录下新建 locales 文件夹,继续新建对应语言的文件夹 (例如:enzh),然后创建 translation.json

例:public/locales/en/translation.json:

{
  "Welcome to React": "Welcome to React and react-i18next"
}

修改 i18n 初始化:

import React from 'react';
import ReactDOM from 'react-dom';
import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import { useTranslation, initReactI18next } from 'react-i18next';

i18n
  // load translation using xhr -> see /public/locales
  // learn more: https://github.com/i18next/i18next-xhr-backend
  .use(Backend)
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    fallbackLng: 'en',
    debug: true,

    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
  });

function App() {
  const { t } = useTranslation();

  return <h2>{t('Welcome to React')}</h2>;
}

// append app to dom
ReactDOM.render(<App />, document.getElementById('root'));

方式二:请求后台数据

Basic sample with XHR JSON:

继续安装插件:

npm install i18next-xhr-backend i18next-browser-languagedetector i18next-multiload-backend-adapter --save

使用实例:

import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import i18n from 'i18next';
import XHR from 'i18next-xhr-backend';
import BackendAdapter from 'i18next-multiload-backend-adapter';
import LanguageDetector from 'i18next-browser-languagedetector';
import { useTranslation, initReactI18next } from 'react-i18next';

i18n
  // learn more: https://github.com/i18next/i18next-multiload-backend-adapter
  .use(BackendAdapter)
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    lng: navigator.language,
    fallbackLng: 'en',
    debug: true,
    preload: navigator.languages,
    interpolation: {
      escapeValue: false // not needed for react as it escapes by default
    },
    backend: {
      backend: XHR,
      allowMultiLoading: true,
      // learn more: https://github.com/i18next/i18next-xhr-backend
      backendOption: {
        loadPath: function(lngs, namespaces) {
          console.log(lngs, namespaces);
          return 'https://my-json-server.typicode.com/TserHub/Json/qinwm?lng={{lng}}&ns={{ns}}';
        },
        addPath:
          'https://my-json-server.typicode.com/TserHub/Json/qinwm?lng={{lng}}&ns={{ns}}'
      }
    }
  });

function App() {
  const { t } = useTranslation();

  return <h2>{t('Welcome to React')}</h2>;
}

// loading component for suspense fallback
function Loader() {
  return <div>Loading...</div>;
}

// append app to dom
ReactDOM.render(
  <Suspense fallback={<Loader />}>
    <App />
  </Suspense>,
  document.getElementById('root')
);

更多 i18n 的详细配置 和 使用方法,请自行去参考资料查找。