React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > React 使用 i18next

在 React 中使用 i18next的示例

作者:啵啵怪_

这篇文章主要介绍了在 React 中使用 i18next,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1. 安装依赖

npm i i18next react-i18next i18next-browser-languagedetector

2. 在src下创建i18n文件夹

!

2.1 common下的zh-CN.js

{
  "common": {
    "personSetting": "个人设置",
    "modifyPassword": "修改密码",
    "currentTime": '当前时间是 {{time}}',
  }
}

2.2 common下的en-US.js

{
  "common": {
    "personSetting": "Personal settings",
    "modifyPassword": "change Password",
    "currentTime": 'Current time is {{time}}',
  }
}

2.3 在common的index.js文件中引入

import en_common from './en-US/translation.json'
import zh_common from './zh-CN/translation.json'

export const langCommon = { en_common, zh_common }

2.4 在resources.js中引入common模块的翻译

import { langCommon } from './locales/common' //公共需要翻译的内容
// 把所有的翻译资源集合
const resources = {
  en: {
    translation: {
      ...langCommon.en_common
    },
  },
  zh: {
    translation: {
      ...langCommon.zh_common
    },
  }
}
export { resources }

2.5 utils下初始化语言的方法

export function initLangage() {
  let lang = localStorage.getItem('language') || navigator.language // 获取浏览器的语言环境,兼容IE的写法
  if (lang) {
    lang = lang.substr(0, 2).toLowerCase() // 截取前两位字符,并转化为小写
    return lang
  } else {
    return 'en'
  }
}

2.6 i18n.js代码如下

import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import LanguageDetector from 'i18next-browser-languagedetector';
import { resources } from '@/i18n/resources'
import { initLangage } from '@/utils'

i18n
  // 检测用户当前使用的语言
  // 文档: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // 注入 react-i18next 实例
  .use(initReactI18next)
  // 初始化 i18next
  // 配置参数的文档: https://www.i18next.com/overview/configuration-options
  .init({
    resources, //资源初始化
    lng: initLangage(),
    interpolation: {
      escapeValue: false, // react already safes from xss
    },
    react: {
      useSuspense: false, // this will do the magic
    },
    debug: false,
  })
export default i18n

3. 在app.tsx中引入

import './i18n/i18n'

4. 页面中使用

import { useTranslation } from 'react-i18next';

const SafetyManage: React.FC = (): React.ReactElement => {
  const { t } = useTranslation();
  return (
    <div >
      <Button
         type="primary"
       >
         {t('common.personnalSetting')}
       </Button>,
       <Button
       >
         {t('common.modifyPassword')}
       </Button>,
       <p>
		  {t('common.currentTime', { time: dayjs().format('MM/DD/YYYY') })}
		</p>
    </div>
  );
}

export default App;

useTranslation 返回的对象包含一个 t 方法,这个方法可以翻译文本。
i18next 提供了插值的用法: 在 t 函数中传递第二个参数,它是一个对象。

在这里插入图片描述

在这里插入图片描述

参考文章:https://www.zadmei.com/qdizjsjz.html

到此这篇关于在 React 中使用 i18next的文章就介绍到这了,更多相关React 使用 i18next内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文