qiandu首先可以自定义配置
文件1 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).init({ resources, lng: 'zh', interpolation: { escapeValue: false, }, }); export default i18n;
zh,json中文Json
{ "header": { "register":"注册", "signin":"登陆", "home": "首页" }, "footer": { "detail" : "版权所有 @ React" }, "home": { "hot_recommended": "爆款推荐", "new_arrival": "新品上市", "joint_venture": "合作企业" } }
en.Json 英文文档
{ "header": { "register":"Register", "signin":"Sign In", "home": "Home" }, "footer": { "detail" : "All rights reserved @ React" }, "home": { "hot_recommended": "Hot Recommended", "new_arrival": "New arrival", "joint_venture": "Joint Venture" } }
切换语言
import i18n from 'i18next'; const changeLanguage= (val) => { i18n.changeLanguage(val); // val入参值为'en'或'zh' };
或者
复制
import React from 'react'; import { useTranslation } from 'react-i18next' export const Home: React.FC = () => { const { t, i18n } = useTranslation() return ( <button onClick={()=>i18n.changeLanguage (i18n.language=='en'?'zh':'en')}>{i18n.language=='en'?'zh':'en'}</button> ); };