使用react-intl V5搭建國際化

介紹

react-intl提供項目國際化的能力

1、基本組件介紹

名稱 功能
IntlProvider 爲樹設置I18N上下文。通常,此組件將包裝應用程序的根組件,以便整個應用程序將在配置的I18N上下文中。以下是可以設置的I18N配置道具:
FormattedMessage 文本轉換基礎組件
FormattedDate 時間格式組件
其他 其他還有很多,詳見官網

2、基本方法介紹

名稱 功能
useIntl 提供intl實例,實例對象上面有很多方法

實操

1、安裝react-intl

npm install react-intl@5 --save
yarn add react-intl@5

2、配置語言文件

在src目錄下面,新建立一個locales目錄,並創建index,language,等其他語言文件表。我的結構如下:

  • language.ts: 包含需要支持語言的枚舉:
export enum Locales{

   ENGLISH='en-us',
   CHINESE='zh-ch'
}
  • index.ts : 最終需要導出的message內容:
import chUs from './ch-us';
import  { Locales } from './language';
import zhCh from './zh-ch';

const localesMessage={
    
    [Locales.CHINESE]:zhCh,
    [Locales.ENGLISH]:chUs
}

export default localesMessage;
  • zh-ch.js|ch-us 分別對應不同語言的索引內容如:
export default {
    'home':'主頁'
}
export  default {
    'home':'Home'
}

3、使用IntlProvider包裹根目錄組件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
import { IntlProvider } from 'react-intl';  //這裏導入
import { Locales } from '@/locales/language';
import localesMessage from '@/locales';


const local=Locales.CHINESE; //使用那種語言


ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
       // messages 參數代表要使用那個語言的配置文件
       <IntlProvider messages={localesMessage[local]} locale={local} defaultLocale={local}>
        <App />
       </IntlProvider>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

4、使用FormattedMessage組件,達到語言翻譯的效果

// 這裏home會根據,上面寫的配置文件,翻譯成中文或者其他語言文案
<FormattedMessage id='home' />
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章