当前位置: 代码迷 >> 综合 >> React i18n 国际化 [TypeScript]
  详细解决方案

React i18n 国际化 [TypeScript]

热度:98   发布时间:2024-02-27 22:53:06.0

安装

yarn add i18next react-i18next i18next-browser-languagedetector

多语言文件

zh-cn.json

{"home":"首页"
}

en-us.json

{"home":"Home"
}

i18n.tsx

import i18n from "i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import enUsTrans from "./en-us.json";
import zhCnTrans from "./zh-cn.json";
import { initReactI18next } from 'react-i18next';i18n.use(LanguageDetector) //获取当前浏览器语言
.use(initReactI18next) 
.init({//资源文件resources: {enUs: {translation: enUsTrans,},zhCn: {translation: zhCnTrans,},},fallbackLng: "zhCn",debug: false,interpolation: {escapeValue: false,},
})export default i18n;

app.tsx引用i18n.tsx

import './i18n'const App: React.FC = () => {}

使用方法


import { useTranslation, Trans, Translation } from 'react-i18next'const App: React.FC = () => {let { t ,i18n} = useTranslation()return (<div >{/* 3种常用使用方式 */}<div>{t('home')}</div><div><Trans>home</Trans></div><Translation>{t => <div>{t('home')}</div>}</Translation><div><button onClick={()=>i18n.changeLanguage(i18n.language=='en'?'zh':'en')}>{i18n.language=='en'?'zh':'en'}</button></div></div>)
}export default App

 

  相关解决方案