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>
    );
};

posted @ 2023-02-28 09:49  前端导师歌谣  阅读(129)  评论(0)    收藏  举报  来源