react項目實現國際化i18n


本篇教程將從零開始實現一個支持多語言功能的demo

0x00 准備

1. 通過create-react-app 新建項目

npx create-react-app my-app

2. 安裝i18n所需的庫

npm install react-i18next i18next i18next-browser-languagedetector i18next-http-backend --save

其中,i18next-browser-languagedetector庫用於添加語言切換功能,可支持自動檢測環境,切換到正確的語言,也可以在url中指定語言

3.修改App.js

實現一個用於展示的最小主頁

import './App.css';

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

  return (
    <div className="App">
      <header className="App-header">
        <p>
          HelloWorld
        </p>
      </header>
    </div>
  );
}

export default App;

0x01 實現最簡多語言功能

創建i18n.js,該文件在目錄中與index.js同級。

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

// the translations
// (tip move them in a JSON file and import them)
const resources = {
    en: {
        translation: {
            "HelloWorld": "HelloWorld"
        }
    },
    zh_CN: {
        translation: {
            "HelloWorld": "你好世界"
        }
    }
};

i18n
    .use(initReactI18next) // passes i18n down to react-i18next
    .init({
        resources,
        lng: "zh_CN", //設置當前語言

        keySeparator: false, // we do not use keys in form messages.welcome

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

export default i18n;

不同語言的翻譯內容填寫在resources中,按照以上格式填寫。上邊我們對HelloWorld提供了兩種語言的翻譯,並設置當前語言為中文(代碼zh_CN)

然后在index.js導入i18n.js

import './i18n';

編輯app.js

import './App.css';
import { useTranslation } from 'react-i18next';

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

  return (
    <div className="App">
      <header className="App-header">
        <p>
          {t("HelloWorld")}
        </p>
      </header>
    </div>
  );
}

export default App;

如上所示,t("HelloWorld")實現了對HelloWorld字符串的翻譯。
運行項目

npm start

我們會看到主頁顯示出了"你好世界"

當我們把i18n.js的lng字段改為"en",再次刷新頁面,會發現主頁顯示變為了"HelloWorld"

0x02 (待更新)

參考文檔

react-i18next官方文檔
i18next 官方文檔
i18next-browser-languagedetector github項目主頁
i18next-http-backend github項目主頁


免責聲明!

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



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