react+hook+ts项目总结-React国际化react-i18next
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" } }
在类组件中使用withTranslation高阶函数完成
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import './i18n/config'; // 引用配置文件 ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') );
函数组件
import React from 'react'; import { useTranslation, Trans } from 'react-i18next' export const Home: React.FC = () => { const { t } = useTranslation() return ( <div> <h1>{t('header.home')}</h1> <ul> <li>{t('home.hot_recommended')}</li> {/* 还有一种方式 */} <li><Trans>home.new_arrival</Trans></li> </ul> </div> ); };
切换语言
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> ); };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南