前端國際化, 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 的詳細配置 和 使用方法,請自行去參考資料查找。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM