React-intl

React-intl Internationaliztion API

API應用環境

  • React-intl的應用依賴於Internationaliztion API,這些APIs現代瀏覽器和NodeJS(>0.12)內涵;html

  • 對於老版瀏覽器須要搭建一些環境node

React-intl簡要介紹

  • React-intl是FormatJS的一部分,內置實現Date/Number/Time的國際格式化;react

  • 能夠自定義映射關係,完成值對之間的替換(這是這篇文章的主要內容);webpack

  • 經過獲取瀏覽器的language來設置顯示中文/英文(經過自定義映射,而非自動全文轉換);git

  • 經常使用於實現靜態內容,如按鈕文字,公司名稱的轉換;github

React框架結合國際化所須要的依賴包

"babel-core": "^6.22.1",
"babel-loader": "^6.2.10",
"babel-preset-env": "^1.1.8",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.22.0",
"copy-webpack-plugin": "^4.0.1",
"html-webpack-plugin": "^2.26.0",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-intl": "^2.2.3",
"webpack": "^2.2.0",
"webpack-del-plugin": "0.0.1",
"webpack-dev-server": "^1.16.2",
"webpack-notifier": "^1.5.0"

React-intl格式化語法

該部分有詳細的介紹,所以忽略web

自定義國際型格式化

重點部分:該項目demo單一功能(internationalization) demo中每一部分都有詳細的講解chrome

  • 不知道這個功能是很蹩腳,仍是蹩腳,網上的例子幾乎沒有,官網的例子……我已經無言了,建議不要看官網了*npm

index.jssegmentfault

import React from 'react';
import ReactDOM from 'react-dom';
// 從'react-intl'中引入addLocaleData,IntlProvider,FormattedMessage三個格式化組件;
import {addLocaleData,IntlProvider,FormattedMessage} from 'react-intl';
/*
*引入與navigator.languages[0]所對應的語言;
*若是沒有引入對應的語言,會使用默認的「en」;
*致使FormattedMessage的映射不會成功;
*/
import zh from 'react-intl/locale-data/zh';
import en from 'react-intl/locale-data/en';
/*
*引入自定義的映射表;
*經過與FormattedMessage的id值來當索引映射返回值;
*/
import zh_CN from './locale/zh_CN';
import en_US from './locale/en_US';
import App from './components/app';
/*
*messages是render()時IntlProvider組件所傳的props,屬性名固定:messages;
*messages返回值爲映射表,好比:'react-intl/locale-data/zh'&&'./locale/zh_CN';
*/
let messages = {};
messages["en-US"] = en_US;
messages["zh-CN"] = zh_CN;
/*
*獲取瀏覽器設置的語言;
*按我demo中的設置,返回["zh-CN", "zh", "en-US", "en"],排序與語言設置順序一直;
*/
const languages = navigator.languages;
const currentLang = languages[0];
console.log("languages: ", languages);
console.log("language: ", currentLang);
// 載入語言數據;
//載入一個addLocaleData(zh);
//載入多個;
addLocaleData([...zh,...en]);

ReactDOM.render(
    // IntlProvider爲'react-intl'指定的包裹組件名;
    <IntlProvider locale={currentLang} messages={messages[currentLang]}>
        <App />
    </IntlProvider>,
    document.body
)

/*
瀏覽器languages大全:
"af", "sq", "ar-SA", "ar-IQ", "ar-EG", "ar-LY", "ar-DZ", "ar-MA", "ar-TN", "ar-OM",
    "ar-YE", "ar-SY", "ar-JO", "ar-LB", "ar-KW", "ar-AE", "ar-BH", "ar-QA", "eu", "bg",
    "be", "ca", "zh-TW", "zh-CN", "zh-HK", "zh-SG", "hr", "cs", "da", "nl", "nl-BE", "en",
    "en-US", "en-EG", "en-AU", "en-GB", "en-CA", "en-NZ", "en-IE", "en-ZA", "en-JM",
    "en-BZ", "en-TT", "et", "fo", "fa", "fi", "fr", "fr-BE", "fr-CA", "fr-CH", "fr-LU",
    "gd", "gd-IE", "de", "de-CH", "de-AT", "de-LU", "de-LI", "el", "he", "hi", "hu",
    "is", "id", "it", "it-CH", "ja", "ko", "lv", "lt", "mk", "mt", "no", "pl",
    "pt-BR", "pt", "rm", "ro", "ro-MO", "ru", "ru-MI", "sz", "sr", "sk", "sl", "sb",
    "es", "es-AR", "es-GT", "es-CR", "es-PA", "es-DO", "es-MX", "es-VE", "es-CO",
    "es-PE", "es-EC", "es-CL", "es-UY", "es-PY", "es-BO", "es-SV", "es-HN", "es-NI",
"es-PR", "sx", "sv", "sv-FI", "th", "ts", "tn", "tr", "uk", "ur", "ve", "vi", "xh",
"ji", "zu"];*/

app.js

/*
    基本用法:
    import React, {Component} from 'react';
    import {FormattedMessage} from 'react-intl';
    
    class App extends Component {
        constructor(props) {
            super(props);
        }
        render() {
    
            /* 
            *FormattedMessage組件中的信息parser後顯示以<span>包裹的文本;
            *能夠經過tagName指定其它標籤包裹;
            *以id屬性的值"hello"爲索引——索引到自定義的映射表'./locale/zh_CN'中去;
            *messages['hello']——messages爲父組件IntlProvider的props的messages屬性;
            *若沒有上述的返回值,則顯示defaultMessage的值"React Intl Translations Example";
            */
            /*
            *FormattedMessage添加子元素或ReactElement;
            *  <FormattedMessage id="hello">
            *      {(formattedValue)=>(
            *          <em>{formattedValue}</em>
            *      )}
            *  </FormattedMessage>
            */
            return (
                <div>
                    <h1>
                        <div>
                            <FormattedMessage
                                id="hello"
                                defaultMessage="React Intl Translations Example"
                            />
                        </div>
                    </h1>
    
                    <h4>
                        <FormattedMessage
                            tagName = 'p'
                            id='superHello'
                            defaultMessage="Locales:北京"
                            values={{
                                someone:'zxdobest'
                            }}
                        />
                    </h4>
                    <h2>
                        <FormattedMessage id="hello">
                            {(formattedValue)=>(
                                <em>{formattedValue}</em>
                            )}
                        </FormattedMessage>
                    </h2>
                </div>
            );
        }
    }
    
    export default App;
    */


//
輸出HTML塊結構;
import React from 'react';
import { injectIntl, intlShape, FormattedMessage } from 'react-intl';

const ChildComponent = ({ intl }) => {
    //傳入的{intl}名稱不可更改;
    console.log(React.PropTypes)
    const getMessage = intl.messages;
    return(
        <section>
            {/*
                *經過intl.messages獲取映射屬性的方法;
                * 能夠和任意內容(如:HTML標籤)組合;
                * */}
            <a>{getMessage.hello}</a>
            {/*經過FormattedMessage格式化,能夠傳入參數{values}*/}
            <FormattedMessage
                tagName = 'p'
                id='superHello'
                defaultMessage="Locales:北京"
                values={{
                    someone:'zxdobest'
                }}
            />
            {/*
               *這種結構,類同於intl.messages.superHello能夠和其它內容任意組合;
               *能且僅能獲取superHello的映射;
               * 目前還沒有找到若是在第一種方法中傳入values;
            */}
            <FormattedMessage id="superHello" values={{
                someone:'mihuartuanr'
            }}>
                {(formattedValue)=>(
                    <p>{formattedValue}</p>
                )}
            </FormattedMessage>
        </section>
    );
}

ChildComponent.propTypes = {
    intl: intlShape.isRequired
}

export default injectIntl(ChildComponent);

常見問題

  1. [React Intl] Missing locale data for locale: "zh-CN". Using default locale: "en" as fallback.

  • 要引入所設locale的語言庫import enLocaleData from 'react-intl/locale-data/zh'該文件爲react-intl包自動下載——還有一個好處:在咱們引入另外一個自定義的映射時,依舊能夠使用react-intl原有的數字/時間等數據的國際格式化;

    • 添加指定語言庫addLocaleData(enLocaleData);

  1. 設置&獲取瀏覽器的locale

    • chrome:
      chrome設置——高級設置——語言和輸入設置

    • js獲取瀏覽器語言設置:

      let languages = navigator.languages;
      console.log("languages: ", languages);
      //=>languages: ["zh-CN", "zh", "en-US", "en"]

demo使用方法

  • 安裝有nodejs和webpack環境;

  • 克隆或下載下來的文件夾進行npm init -y

  • 安裝依賴npm install

  • 經過npm run start利用本地服務器查看

  • 打開瀏覽器localhost:3000查看頁面

使用效果預覽

自動映射瀏覽器語言設置

參考文檔

  1. Format.JS

  2. github/yahoo/react-intl

  3. NPM/react-intl

  4. Internationalization in React

  5. Segmentfault/webFunc

相關文章
相關標籤/搜索