乐闻世界logo
搜索文章和话题
 在项目中快速使用React-i18next

在项目中快速使用React-i18next

小白的头像
小白

2023年05月24日 11:45· 阅读 3558

React-i18next

是一款强大的国际化框架for react /react native,基于 i18next,其作用就是项目可以实现多语言。

下面我将介绍一下react-i18n的使用

安装

shell
# npm $ npm install react-i18next i18next --save

初始化

配置选项

  • resource: 资源初始化
  • lng: 使用的语言
  • fallbackLng: 兜底语言
  • debug: 将日志打印到控制台
  • interpolation: 插值。允许将动态值即成到翻译中 escapeValue --->是否转义传递的值

i18n.ts

ts
import i18n from "i18next"; import {initReactI18next } from "react-i18next"; import ja from "./ja.json"; import en from "./en.json"; import zh from "./zh.json"; export const resources = { "ja": { translation: ja }, "en": { translation: en }, "zh": { translation: zh } } i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ resources, lng: "en", // if you're using a language detector, do not define the lng option fallbackLng: "en", debug: true, interpolation: { escapeValue: false // react already safes from xss => https://www.i18next.com/translation-function/interpolation#unescape } });

加载

需要在项目入口加载,目的就是初始化,加载资源文件,后续在组件中可以正常翻译。不进行加载的话,下面所说的组件的使用带来的效果就是界面显示的都是key 值而不是对应的value值。这里我以小程序举例

app.tsx

tsx
import './i18n/i18n'

组件中使用

t('key')括号内的内容是翻译文件中对应的key

  1. 使用hook方式

    tsx
    import React from 'react'; // the hook import { useTranslation } from 'react-i18next'; function MyComponent () { const { t, i18n } = useTranslation(); return <h1>{t('test_text')}</h1> }
  2. 使用HOC方式

    tsx
    import React from 'react'; // the hoc import { withTranslation } from 'react-i18next'; function MyComponent ({ t }) { return <h1>{t('test_text')}</h1> } export default withTranslation()(MyComponent);
  3. 使用 render prop

    tsx
    import React from 'react'; // the render prop import { Translation } from 'react-i18next'; export default function MyComponent () { return ( <Translation> { t => <h1>{t('test_text')}</h1> } </Translation> ) }

    翻译json文件中

    json
    { 'test_text': 'hello world' }
  4. 使用Trans组件

    tsx
    import React from 'react'; import { Trans } from 'react-i18next'; export default function MyComponent () { return <Trans><H1>Welcome to React</H1></Trans> } // the translation in this case should be "<0>Welcome to React</0>": "<0>Welcome to React and react-i18next</0>"

如果是在ts文件中使用

ts
import i18next from './i18n' i18next.t('my.key')
标签: