i18n在react项目中的使用

文档地址
https://react.i18next.com/guides/quick-start

npm install react-i18next i18next --save

1、建立文件夹
src/i18n
src/i18n/configs.ts
src/i18n/en.json
src/i18n/zh.json

2、具体代码

src/i18n/configs.ts

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them separated from your code: https://react.i18next.com/guides/multiple-translation-files)
const resources = {
  en: {
    translation: {
      "Welcome to React": "Welcome to React and react-i18next"
    }
  },
  fr: {
    translation: {
      "Welcome to React": "Bienvenue à React et react-i18next"
    }
  }
};

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en", // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources
    // you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage
    // if you're using a language detector, do not define the lng option

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

  export default i18n;
src/i18n/en.json 
src/i18n/zh.json

{
    "xxx1": {
    	"key": "value",
    },
    "xxx2": {
    	"key": "value",
    },
}

3、在入口文件main.js引入

src/main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './i18n/configs' // 直接引入就好
import {Provider} from 'react-redux';
import mixedstore from './redux/store/store'
import {PersistGate} from 'redux-persist/integration/react'
ReactDOM.render(
  <React.StrictMode>
      <Provider store={mixedstore.store}>
          <PersistGate persistor={mixedstore.persistor}>
              <App />
          </PersistGate>
      </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

4、通过i18n的changeLanguage方法改变当前语言

i18n.changeLanguage(action.payload)

5、语言显示


import React from 'react';
import {Typography} from 'antd'
import {Link} from 'react-router-dom'
import {useTranslation} from 'react-i18next'
export const Index = props =>{
    const {t}=useTranslation();
    return(
                <div>
                    <Typography.Text type="danger">¥ {price} {t("xxx1.key")}</Typography.Text>
                </div>
    )
}
export default Production
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值