react 使用i18next,react-i18next 實現多語言切換


i18next,react-i18next 插件

項目環境

react + umi

使用步驟

  1. 安裝
    npm install i18next --save
    npm install react-i18next --save

2.在src文件下新建配置文件 lang.js

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
// not like to use this?
// have a look at the Quick start guide
// for passing in lng and translations on init

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({
    resources: {
      EN: {
        translations: require("@/assets/lang/en-US.json"),
      },
      CN: {
        translations: require("@/assets/lang/zh-CN.json"),
      },
    },
    // fallbackLng: 'zh-CN', // 使用LanguageDetector 取消注釋
    fallbackLng: localStorage.getItem("lang") === "EN" ? "EN" : "CN",
    debug: true,

    // have a common namespace used around the full app
    ns: ["translations"],
    defaultNS: "translations",

    keySeparator: false, // we use content as keys

    interpolation: {
      escapeValue: false, // not needed for react!!
    },

    react: {
      wait: true,
    },
  });

export default i18n;

  1. 靜態資源下新建json語言包,有幾種語言建幾種包,文件名
    例:
    中文包 zh-CN.json
{
  "你好": "你好",
  "提交": "提交"
}

英文包 en-US.json

{
  "你好": "Hello",
  "提交": "Submit"
}

  1. 使用
    將配置文件引入到首頁入口文件
import "@/lang";

在每個文件夾里使用

  • i18next的使用(簡單方便,但是在當前頁面不能及時刷新)
import i18next from "i18next";

// 這種寫法,必須手動刷新,不能及時刷新
 <div>{i18next.t("你好")}</div>
 
  • react-i18next的使用(使用復雜,但在當前頁面切換可以不刷新切換),使用時需要包裹當前組件
import { withTranslation } from "react-i18next";

 <div style={{ margin: 10 }}>
    <p>{this.props.t("你好")}</p>
  </div>

export default withTranslation("translations")(LongTxt);
 

hook寫法使用

import { useTranslation } from "react-i18next";

const Dashboard = (props) => {
    const { t } = useTranslation();
    return <div>{t("品類廣場")}</div>
}

附 目錄結構


免責聲明!

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



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