i18next国际化(react)

作者 : admin 本文共1153个字,预计阅读时间需要3分钟 发布时间: 2024-06-11 共1人阅读

 i18next官网库(https://react.i18next.com/)

安装命令  npm install react-i18next i18next –save
 

includes/i18n.js

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import zh from '../locales/zh.json';
import en from '../locales/en.json';


const resources = {

    //对应的英文
  en,
  //对应的中文
  zh, 
};

i18n
  .use(initReactI18next) 
  .init({
    resources,
    // 默认语言改为中文
    lng: "zh", 
    //这个是一个中文切换到因英文如果切换错误会默认切换到中文
    fallbackLng: "zh",
    interpolation: {
      escapeValue: false 
    }
  });

  export default i18n;

locales/en.json

{
    
    "translation": {
     
      "Welcome to React": "Welcome to React ",
      "Learn React" : "Learn React"
    }
  }

zh.jaon

{
    "translation": {
    
      "Welcome to React": "欢迎使用 React",
      "Learn React" : "学习 React"
    }
}

app.js

import React,{useRef} from 'react'
import "./includes/i18n"
import { useTranslation } from 'react-i18next';
import {requestMsgApi} from "./api/message"

export default function App() {

  //获取当前组件实例
  const componentRef = useRef(null);
  // 在需要的地方获取组件实例
  const instance = componentRef.current;


  //就可以简单地插入我们的文本
  const { t, i18n } = useTranslation();

  //设置语言切换
  const changeLangage =()=>{
    //通过调用这个i18nchangeLanguage这样一个方法就可以简单的修改我们当前的语言

    i18n.changeLanguage(i18n.language === "en" ? "zh" : "en");

  }




  return (
    
      

{t('Welcome to React')}

{t('Learn React')}

{/* i18n.language 可查看所在中文还是英文 */} {/* changeLangage 绑定点击事件 */}
) }

本站无任何商业行为
个人在线分享 » i18next国际化(react)
E-->