關(guān)于React國際化方案 2019-08-09

今天也是平凡的一天,在公司里調(diào)調(diào)UI、改改BUG,順便就寫點前幾天集成的國際化方案吧

前幾天,BOSS找到我說,要把app翻譯一下銷售到國外去,接軌下國際市場,讓我整理下需要翻譯的文案。首先想到的就是,應(yīng)該要做國際化處理了,之前也看過關(guān)于國際化的一些方案,于是翻閱資料后,就利用react-intl集成了一個簡單的國際化方案。

安裝過程就不多說了,使用npm安裝,如下指令:npm install react-intl --save

首先,先創(chuàng)建翻譯方案存放的目錄

├── dist
├── src
│   └── locales      // 多語言文件存放目錄,推薦按照頁面進行組織
│         ├── en-US
│         │   ├── page1.js
│         │   ├── page2.js
│         │   └── index.js
│         │ 
│         └── zh-CN
│            ├── page1.js
│            ├── page2.js
│            └── index.js
└── package.json

大概結(jié)構(gòu)就是這樣,使用locales目錄存放各國語言的翻譯方案,文件名以語言-國家的形式命名,里面則按實際頁面創(chuàng)建js文件,index.js進行整合。

文件內(nèi)容大概是這樣子的:
page.js

export default {
  'app.startup.tips.logging': 'Logging in to device...',
  'app.startup.tips.device': 'Getting device info...',
};

index.js

import page1 from './page1.js';
import page2 from './page2.js';
export default {
 ...page1 ,
...page2 
};

然后再自定義一個多語言組件LocaleProvider,引入react-intl并導入語言包,對其進行一層封裝。

import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { IntlProvider, addLocaleData } from 'react-intl';

// 引入 react-intl 多語言包
import en from 'react-intl/locale-data/en';
import zh from 'react-intl/locale-data/zh';

// 引入 locale 配置文件
import en_US from '../../locales/en-US';
import zh_CN from '../../locales/zh-CN';

// 設(shè)置語言包
addLocaleData([...en, ...zh]);

const localeInfo = {
  'zh-CN': {
    appLocale: 'zh',
    appMessages: zh_CN,
  },
  'en-US': {
    appLocale: 'en',
    appMessages: en_US,
  },
};

class LocaleProvider extends PureComponent {
  render() {
    const { locale, children } = this.props;

    return (
      <IntlProvider
        locale={localeInfo[locale].appLocale}
        messages={localeInfo[locale].appMessages}
      >
          {React.Children.only(children)}
      </IntlProvider>
    );
  }
}

LocaleProvider.propTypes = {
  locale: PropTypes.string.isRequired,
  children: PropTypes.element.isRequired,
};

export default LocaleProvider;

由外部傳入locale控制語言包的加載,使用LocaleProvider包裹根組件

import LanguageProvider from './components/LocaleProvider';
import AppRouter from './router';
import { getLocale } from './utils/locale';

const locale = getLocale();

ReactDOM.render(
  <LanguageProvider locale={locale}>
    <AppRouter />
  </LanguageProvider>,

  ICE_CONTAINER
);

這里使用了react-router-dom做路由跳轉(zhuǎn),所以外層是一個封裝的AppRouter組件,如果集成redux就應(yīng)該是Provider

locale由瀏覽器語言決定,使用getLocale獲取

/**
 * 獲取當前語言
 */
function getLocale() {
  if (!window.localStorage.getItem('lang')) {
    window.localStorage.setItem('lang', navigator.language);
  }
  return localStorage.getItem('lang');
}

這里也可以做成state,動態(tài)控制其locale

接下來就是對代碼中的方案進行翻譯替換,在需要翻譯的類里引入

import { injectIntl } from 'react-intl';

并在類頭上加入injectIntl注解

@withRouter @injectIntl
class Startup extends Component {
   //.....
}

此時,this.props中就會有一個intl對象,其結(jié)構(gòu)大概如下圖:

79445030-1D0D-42A5-BA8C-23357135FEF6.png

主要包含日期格式化(formatDate,formatTime,formatRelativeTime)、字符串格式化(formatMessage,formatHTMLMessage)、數(shù)字格式化(formatNumber,formatPlural)功能。其具體翻譯功能及使用方法,推薦翻閱github

而翻譯文本,主要使用formatMessage方法

componentDidMount() {
    let {intl: { formatMessage },} = this.props;
    this.formatMessage = formatMessage;
    // .......
}

在生命周期componentDidMount中,取出并保存formatMessage方法,在需要翻譯的地方,如下使用:

this.setState({text: this.formatMessage({id:'app.startup.tips.device'}) });

參數(shù)為locales里配置的對應(yīng)的id對象

做到這里,一個簡單的國際化集成就完成了。其主要工作量,主要還是翻譯方案的地方,還得找專業(yè)人士進行翻譯,自己蹩腳的英語及機翻還是差太多。。。。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容