React 中使用 i18next

安装依赖

# npm
npm i i18next react-i18next i18next-browser-languagedetector
# pnpm
pnpm add i18next react-i18next i18next-browser-languagedetector

i18next 提供了翻译的基本能力。
react-i18next 是 i18next 的一个插件,用来降低 react 的使用成本。
i18next-browser-languagedetector 是用来检测浏览器语言的插件。

创建i18n文件夹

目录

	src
	└──i18n
	  └──locales
	  ┊  ├──en-US
	  ┊  ┊  └──index.ts
	  ┊  └──zh-CN
	  ┊     └──index.ts
	  └──index.ts

locales/en-US/index.ts

export default {
  common: {
    login: 'Login',
    register: 'Register',
  }
}

locales/zh-CN/index.ts

export default {
  common: {
    login: '登录',
    register: '注册',
  }
}

i18n/index.ts

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import translationEN from './locales/en-US';
import translationZH from './locales/zh-CN';

const resources = {
  en: {
    translation: translationEN
  },
  zh: {
    translation: translationZH
  }
};
i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    debug: true,
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    // language resources
    resources
  });

export default i18n;

使用

在main.tsx中引入

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import './i18n'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

页面中使用

import { useTranslation } from 'react-i18next';

const App: React.FC = (): React.ReactElement => {
  const { t } = useTranslation();
  return (
    <div >
         {t('common.personnalSetting')}
    </div>
  );
}

export default App;

切换语言

import i18n from 'i18next';

const changeLanguage= (val) => {
	i18n.changeLanguage(val); // val入参值为'en'或'zh'
};

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哚啦A孟

谢谢鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值