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>
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM