国际化

2021-09-16  本文已影响0人  易路先登

一、 i18n

Internationalization 首末字母与字符数。
能根据不同的语言及地区显示相应的界面。

原理:
1、语言作为静态资源单独保存:xml,json
2、每种语言对应一个文件
3、切换语言设置时,语言文件也会随之切换
工具:

1、安装

npm install react-i18next i18next --save//原生支持typescript 不需要额外安装声明文件

2、使用

(1)、目录

i18n
    config.ts
    zh.json
    en.json 
//i18n/config.ts
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import translation_en from "./en.json"
import translation_zh from "./zh.json"
const resources = {
  en: {
    translation: translation_en 
  },
  zh: {
    translation: translation_zh 
  }
};
i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "zh", // 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;
//index.ts
import "i18n/config"//react-i18next会帮我们自动注入

(2)、使用
类组件中使用

import { withTranslation,WithTranslation } from "react-i18next"

class TestComponent extends React.Component<WithTranslation >{
      render(){
            let { t } = this.props
            return <div>{t.header.xxx}</div>
      }
}
export default withTranslation()(TestComponent )

函数组件中使用

import { useTranslation} from "react-i18next"

function TestComponent(){
  const { t } = useTranslation()
  return <div>{t.header.xxx}</div>
}

(3)、i18n的语言切换

import i18n from 'i18next'
i18n.changeLanguage('en')
上一篇 下一篇

猜你喜欢

热点阅读