i18n的学习

这个可以理解为是一个翻译的插件,可以令页面文档呈现多种语言。

先按着官网文档大概看看

安装

npm install react-i18next i18next --save

配置下一步

新建一个文件夹 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,
// or even better, manage them separated from your code: https://react.i18next.com/guides/multiple-translation-files)
const resources = {
  en: {
    translation: {
      "Welcome to React": "Welcome to React and react-i18next"
    }
  },
  fr: {
    translation: {
      "Welcome to React": "Bienvenue à React et react-i18next"
    }
  }
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en", // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources
    // you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage
    // if you're using a language detector, do not define the lng option

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

  export default i18n;

先解释一下这个文件的意思

从上往下,先引入所需的内容一个是i18next,还有一个react-i18next

下面就是两种翻译的方案

其一就是叫en的翻译方案,与之对应的是叫fr的翻译方案(看文档后者应该是法语)

这两种方案内部各有一句话这句出现在左边的话文字内容是完全相同的

那相对应的后面的那句话就是我们最终翻译的内容了

再下面有个叫i18n的,这个就是负责最终装配这个逻辑了


把具体转换内容移动到json文件中。再进行导出到最外面,这样就可以分开管理代码和插件

以上这部分大概有上下两段组成

resources是定义到时候哪些文本换成哪些语言的

resources的常量,里面的结构是这样的
en:{
    translation:{
        "文本1":"文本2"
    }    


},

fr:{
    transtion:{
        "文本3":"文本4"
    }
}
 

显然这个是被分成两种。像本项目里面的话就是一个是英语,一个是繁体

再看看本项目里面i18n的index文件

export const i18nResources = {
  EN: 'EN',
  TW: '繁'
}

i18n.use(initReactI18next).init({
  resources: { [i18nResources.EN]: { translation: enUsTrans }, [i18nResources.TW]: { translation: zhTwTrans } },
  fallbackLng: i18nResources.EN,
  debug: false,
  interpolation: { escapeValue: false }
})

和上面的例子结构差不多

这里的enUsTranszhTwTrans都是从其他页面引来的,有很多需要翻译的字段

大概张这样

{
  "menu_farm": "SOSO農場",
  "menu_game": "遊戲",
  "menu_nft": "NFT市場",
    ...
}

这个是zhTwTrans的一部分,enUsTrans结构也差不多,不过是英文的


再看看项目的一些内容

resources里面有主要的内容,i18n.init({resources})
在上面的i18n.use(initReactI18next)的作用是把i18n转入到react-i18next

 interpolation: {
      escapeValue: false, 
    },

这个貌似是阻止xss攻击的?

  fallbackLng: i18nResources.EN,

这个应该是指默认的语言

就先搞到这里,主要就是大概知道一点就先了,其他api先不烦了hh

猜你喜欢

转载自blog.csdn.net/qq_53563991/article/details/125177894