1. 程式人生 > 其它 >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>