1 introduction

Some projects will require language internationalization and multi-language capabilities.

2 brief introduction

React-intl is part of FormatJS, Yahoo’s open source language internationalization project, which provides components and apis that can be bundled with ReactJS.

3 introduction

React-intl provides two ways to use it, either by calling the API directly or by referring to the React component.

Call the API directly

  1. The importinjectIntl
import { injectIntl, FormattedMessage } from 'react-intl'
Copy the code
  1. Inject in the componentinjectIntl
export default connect(state => { return { ... state }; })(injectIntl(App));Copy the code

or

export default connect(mapStateToProps,mapActionCreators)(injectIntl(App))
Copy the code
  1. useintlobject

We now have an intL object on the props of the component that provides the same method as the component we described above. If we want to display a string, we can use the formatMessage method:

Const {intl} = this. Props; let demo = intl.formatMessage({id: 'intl.name'});Copy the code
  1. application
<Input placeholder={formatMessage(demo.placeholder)}/>
Copy the code

Use the React componentdefineMessagesTo convert to a string

  1. The importinjectIntlanddefineMessages
import { FormattedMessage, injectIntl, defineMessages } from "react-intl";
Copy the code
  1. Inject in the componentinjectIntl
export default connect(state => { return { ... state }; })(injectIntl(App));Copy the code

or

export default connect(mapStateToProps,mapActionCreators)(injectIntl(App))
Copy the code
  1. usedefineMessagesDefine andintlobject
const {intl: { formatMessage }} = this.props; Const demo = defineMessages({placeholder: {id: "modal.inviter. Placeholder ", defaultMessage:" please input the inviter's name ",},});Copy the code

4. The application

<Input placeholder={formatMessage(demo.placeholder)}/>
Copy the code

Conclusion: The common point of both methods is that injectIntl is injected into the component. The difference is that the first method can be called directly and the second method needs to be transformed

Several common usages

wraps around the outermost layer of the component that requires language internationalization, providing key-value pairs containing ids and strings for all components contained within it.

Date/time

  1. <FormattedDate />For formatting dates, the ability to format a timestamp into a date format in different languages.

Pass the timestamp as an argument:

<FormattedDate 
    value={new Date(1459832991883)}
/>
Copy the code

Output result:

<span>4/5/2016</span>
Copy the code
  1. <FormattedTime>Used for formatting time, effect and<FormattedDate />Similar.

Pass the timestamp as an argument:

<FormattedTime 
   value={new Date(1459832991883)}
/>
Copy the code

Output result:

<span>1:09 AM</span>
Copy the code
  1. <FormattedRelative />This component displays the relationship between a timestamp passed into the component and the current time, such as”10 minutes ago“.

Pass the timestamp as an argument:

<FormattedRelative 
    value={Date.now()}
/>
Copy the code

Output result:

<span>now</span>
Copy the code

Output after 10 seconds:

<span>10 seconds ago</span>
Copy the code

Output after 1 minute:

<span>1 minute ago</span>
Copy the code

Digital quantifiers

  1. <FormattedNumber /> The main use of this component is to place a comma on a string of numbers, such as 10000, which in Chinese would be 10,000 with a comma every four digits, and 10,000 with a comma every three digits in English.

Pass a number as an argument:

<FormattedNumber 
    value={1000}
/>
Copy the code

Output result:

< span > 1000 < / span >Copy the code
  1. <FormattedPlural />This component can be used to format quantifiers, which are not very useful in Chinese context. For example, if we say one chicken leg, the quantifier is’ qi ‘. If we say two chicken legs, the quantifier is still ‘qi’. But in the English context, when describing an apple, the quantifier is apple, and when there are two apples, it becomes apples. That’s what this component does.

In the parameters passed to the component, value is the quantity, and the others are quantifiers for different quantities. In the following example, one quantifier is message, and two quantifiers are messages. In fact, the quantifiers that can be passed into components include zero, one, two, few, many, and other, covering all the cases.

<FormattedPlural
    value={10}
    one='message'
    other='messages'/>
Copy the code

The quantifier parameter passed to the component can be a string or a component. We can choose to pass in the component and switch the quantifier between different languages. Output result:

<span>messages</span>
Copy the code

String formatting

  1. <FormattedMessage />This component is used to format strings and is the most frequently used component of all, because basically every string on the UI should be replaced with this component.

For example, we put something like this in the locale configuration file:

Const zhCn = {hello:" Hello world!" }; export default zhCn;Copy the code

To use this component, we write:

<FormattedMessage ID =hello' description= hello' defaultMessage=' Hello world! '/ >Copy the code

The ID refers to the attribute name of the string in the locale configuration file, and the description refers to the description of the string that is substituted for the locale configuration file, which is easy to maintain and will not affect the output. When the ID is not found in the locale configuration file, The output is the value of defaultMessage.

Output results:

<span> Hello world! </span>Copy the code
  1. <FormattedHTMLMessage />The usage of this component and<FormattedMessage />The only difference is that the output string can contain HTML tags, but this is not officially recommended and I won’t give examples of how to use this component.

Code demo

  1. The installation

Assume you have Node.js and NPM installed on your system.

Open the terminal, go to the root directory of the project, and enter the following command to install react-intl:

npm install react-intl -save
Copy the code

Note: To be compatible with all versions of Safari, you need to install INTL as well. Intl comes with most “modern” browsers by default, but Safari and IE11 versions below do not.

To install INTL, enter the following command in the terminal:

npm install intl --save
Copy the code
  1. reference
import { FormattedMessage } from 'react-intl'
Copy the code

Since I’m using ES6 syntax, direct references to components are supported. You can of course use ES5 style references.

require ReactIntl from 'react-intl'
Copy the code
  1. Create a locale configuration file

Here, we name the files zh_cn.js, en_us.js, ja_jp.js, and ko_kr.js, representing the Chinese, American English, Japanese, and Korean configuration packages, respectively.

Write the following code in zh_cn.js:

Const zhCn = {hello:" Hello world!" }; export default zhCn;Copy the code

Write the following code in en_us.js:

const enUs = { hello:"Hello, world!" }; export default enUs;Copy the code

Write the following code in ja_jp.js:

Const jaJp = {hello: Hello! }; export default jaJp;Copy the code

Write the following code in ko_kr.js:

Const koKr = {hello:"안녕, 세계!" }; export default koKr;Copy the code

So we’ve created our locale file.

  1. use<IntlProvider />

Using the
component to wrap components that require language internationalization is similar to the use of in react-redux. When
wraps a component, This component itself and the children contained within it get all the interfaces provided by React- IntL and the contents of the locale configuration file introduced in
.

AddLocaleData: introduces the local LocaleData IntlProvider: the component that the package needs to translate, which is used to pass the FormattedMessage to the subclass language: the text that the package needs to implement in multiple languages

Locale is the abbreviation of transfer to international language, determined by the parameters can be formatted dates, Numbers, when quantifiers which in accordance with the rules of the language, this is the rule is to provide, the intl general browser will built-in this library, but in Safari and IE11 before the need to install, installation method as already mentioned, Please look through it yourself.

Messages is used to pass the configuration file we just defined in Step 3. As you can see from the sample code, we first Import the configuration file with an Import statement and then pass the contents of the configuration file to the messages parameter. All components in the
component can now access the contents of the configuration file.

First, I get the language stored in localStorage, if not set, then I get the browser language navigator. Language, if set, then from localStorage you get the language of your choice.

  1. Implementation effect

  1. Configuration file code

Initialize the load language package

import React from "react"; import PropTypes from "prop-types"; import { IntlProvider, addLocaleData } from "react-intl"; import zh from "react-intl/locale-data/zh"; import en from "react-intl/locale-data/en"; import ja from "react-intl/locale-data/ja"; import ko from "react-intl/locale-data/ko"; import { chooseLocale, getLanguage } from "./.. /.. /lib/tools/utils.js"; const Intl = ({ children }) => { addLocaleData([...zh, ...en, ...ja, ...ko]); const defaultLang = getLanguage(); return ( <IntlProvider locale={defaultLang} messages={chooseLocale()}> {children} </IntlProvider> ); }; Intl.propTypes = { children: PropTypes.node.isRequired, } export default Intl;Copy the code

Switch, display

import enUs from "./.. /locale/en_US"; import zhCn from "./.. /locale/zh_CN"; import jaJp from "./.. /locale/ja_JP"; import koKr from "./.. /locale/ko_KR"; / / get the export function getLanguage () {const lang = the navigator. Language | | the navigator. UserLanguage; // Regular browser language and IE browser const localStorageLang = localstorage.getitem ("lang"); const defaultLang = localStorageLang || lang; return defaultLang; Export function changeHtmlLang(lang) {return document.getelementById ("lang").lang = lang; } export function setLanguage(lang) {const defaultLang = localstorage.setitem ("lang", lang); return defaultLang; } export function chooseLocale() {switch (getLanguage()) {case "en": changeHtmlLang(getLanguage()); return enUs; case "zh": changeHtmlLang(getLanguage()); return zhCn; case "ja": changeHtmlLang(getLanguage()); return jaJp; case "ko": changeHtmlLang(getLanguage()); return koKr; default: changeHtmlLang(getLanguage()); return zhCn; }}Copy the code

The last

Everybody, leave early and leave your footprints. Thank you