zoukankan      html  css  js  c++  java
  • 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>
    }
    

    附 目录结构

  • 相关阅读:
    Debian6.0 linux安装redmine
    Backtrack无线WPA2破解过程
    回溯法解决0-1背包问题
    机试笔记8--栈与优先队列
    计算机网络笔记--数据链路层
    计算机网络笔记--物理层--调制
    计算机网络笔记--物理层--编码
    计算机网络笔记--物理层-概述
    机试笔记7--数学问题
    两种简单的字符串匹配算法
  • 原文地址:https://www.cnblogs.com/cxx9759/p/14596921.html
Copyright © 2011-2022 走看看