其他分享
首页 > 其他分享> > react 国际化

react 国际化

作者:互联网

使用插件: i18next

 安装插件: npm install react-i18next i18next --sav

//App.js
import React, { Component } from 'react'
import './App.css'
import i18n from 'i18next'
import { useTranslation, initReactI18next } from 'react-i18next'
import SiderDemo from './Navi/Navi'
import { Radio } from 'antd'
import cen from './locale/en' //这里的cen 就是 中文配置包,暴露出来的是一个对象 key:value 的形式
import czh from './locale/zh'//这里的czn 就是 英文配置包,暴露出来是一个对象 key:value 的形式
let lng = 'zh'

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources: {
      en: {
        translation: { ...cen }
      },
      zh: {
        translation: { ...czh }
      }
    },
    lng: lng,
    fallbackLng: lng,

    interpolation: {
      escapeValue: false
    }
  })
function onChange(e) {
  if (e.target.value === 'english') {
    lng = 'en'
    i18n
      .use(initReactI18next) // passes i18n down to react-i18next
      .init({
        resources: {
          en: {
            translation: { ...cen }
          },
          zh: {
            translation: { ...czh }
          }
        },
        lng: lng,
        fallbackLng: lng,

        interpolation: {
          escapeValue: false
        }
      })
  } else {
    lng = 'zh'
    i18n
      .use(initReactI18next) // passes i18n down to react-i18next
      .init({
        resources: {
          en: {
            translation: { ...cen } 
}, zh: { translation: { ...czh }
} }, lng: lng, fallbackLng: lng, interpolation: { escapeValue: false } }) } }
 function App() {
 const { t } = useTranslation()
 window.$t = t  //将 t 挂载在 window 上,以至于在其他组建调用时不需要再次引入
return ( 
<div> 
<SiderDemo> 
<div className="lng"> 
<Radio.Group onChange={onChange} defaultValue="chinese">  //当Radio 组件状态改变时,lng也得改变对应的 值
 <Radio.Button value="chinese">中文</Radio.Button> 
 <Radio.Button value="english">English</Radio.Button>
 </Radio.Group> </div> </SiderDemo> </div> ) 
} 
export default App


//需要使用国际化的组件 
//仅为示范例,并无逻辑
 <Header style={{ background: '#000', padding: 0 }}>
                <span
                  style={{
                    color: '#fff',
                    paddingLeft: '2%',
                    fontSize: '1.4em'
                  }}
                ></span>
                <span
                  style={{
                    color: '#fff',
                    paddingLeft: '2%',
                    fontSize: '1.4em'
                  }}
                >
                  {window.$t('cgg')} //这里就是调用国际化cgg 是配置文件里面的 key,展示的便是 key对应的value
                </span>
                <span
                  style={{ color: '#fff', float: 'right', paddingRight: '1%' }}
                >
                  <img src={logo} className="App-logo" alt="logo" />
                </span>
              </Header>

  

标签:国际化,zh,react,i18next,i18n,import,lng
来源: https://www.cnblogs.com/shirleyLive/p/16094666.html