Home >Backend Development >PHP Tutorial >Examples to explain React-intl implementation of multi-language

Examples to explain React-intl implementation of multi-language

小云云
小云云Original
2017-12-12 09:21:032128browse

This article mainly introduces the sample code for implementing multi-language in React-intl. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

The language internationalization function has recently been added to the project.

Language internationalization, some people call it language localization, is actually adding multiple languages ​​to the Web App. Our project currently includes the Chinese version and the English version. Logically speaking, "word-for-word replacement" is not It's a big deal, but is there any money to be made with such a low approach?

At the beginning, I considered the traditional method of adding config files to the entire project. According to different languages ​​and regions, loading different config files can achieve the purpose of interface language switching. Of course, it is precisely because this idea is too naive that it is called the "initial" idea. The internationalization of language is not just about translating the UI text on the interface into another language, but also includes date & time display, numerical display (a comma every 3 digits in the English environment: 1,000), and quantifier display (an apple). is apple, two apples should be apples), and there is even a case where a variable is inserted in the middle of a string ("I ate {count} chicken drumsticks for lunch today")...

So this is not It is not just a simple character replacement problem, but also, we need to easily export a directory and put it in word or page, so that other colleagues can compare and translate it. This is very important! ! Do you want the product manager to make changes directly in the code? Or do you want to search and replace one by one? If you just do it without thinking it through, trust me, you'll pay for this.

As an aspiring coder, you definitely don’t want to add a line of 2934a685527f5cd6bcb20a3dc28499e1 reference to index.html, right? In addition, all the text in the UI belongs to the student who used the picture. Please stand up and get out. If you want to elegantly import something from somewhere in a React project, then replace the text in the interface with c82bfd454240bbe8068ab5889f7b4ae6 components, and finally achieve language internationalization through simple configuration, then we will use React -intl.

For React internationalization, I recommend using React-intl. This library provides React components and APIs to format dates, numbers, strings, etc. Now that we know this library, let’s start using it

Component usage

In order to be more integrated with React, we can use the component method

1 .Install

npm install react-intl --save

2.Add reference

import {IntlProvider, addLocaleData} from 'react-intl';

3.Add locale configuration file

zh-CN.js

const zh_CN = { 'intl.hello': "你好", 'intl.name': '我的名字是 {name}' } export default zh_CN;

en-US.js

const en_US = { 'intl.hello': "hello", 'intl.name': 'my name is {name}' } export default en_US;

4.Use 1905fd125854d59ec1f7dec72e3298cf

This component is used to set the context of i18n, it will wrap the root component of the application so that the entire application will be configured in the context of i18n.
The two most important configuration items are: loacle, the current language environment, messages, and the content of the current language.

If we want to switch languages ​​dynamically, we need to dynamically change these two configurations.

import zhCN from './locale/zh.js';  //导入 i18n 配置文件
import enUS from './locale/en.js';

addLocaleData([...en, ...zh]);

export default class Root extends Component {
  static propTypes = {
    store: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { store , history } = this.props;
    return (
      <IntlProvider locale=&#39;zh&#39; messages={zhCN}>
        <Provider store={store}>
          <Router history={history}>
          </Router>
        </Provider>
      </IntlProvider>
    )
  }
}

5. Use 12e09664183759a27c35bf8019a3976f

Basic usage

<FormattedMessage 
  id="intl.hello"
  defaultMessage={&#39;hello&#39;}
/>

If the current language environment is Chinese, it will display Hello. If it is an English environment, it will display Hello.

Dynamic value transfer

<FormattedMessage
  id="intl.name"
  values={{name: <b>{name}</b>}}
/>

When we defined intl.name, {name} was used in the template. This means that we can dynamically pass values. We can pass a JSON object through the values ​​attribute in FormattedMessage. This will dynamically display our content.

6. Usage of other components

Ract-intl provides us with a wealth of components that can help us process strings, times, and dates. You can check the API yourself, if any If you don’t understand something, I can leave a message.

API Usage

Sometimes we may need to dynamically do internationalization in the code, which requires a dynamic API. Let me briefly introduce how to use

1. Import injectIntl

import { injectIntl, FormattedMessage } from &#39;react-intl&#39;;

2. Inject

## in the component #

export default connect(mapStateToProps,mapActionCreators)(injectIntl(App))

I used Redux in the project. When injecting, it should be as above. If you don’t use Redux, you only need to export defuault injectIntl(App)

3. Use intl object

After the second step of injection, we will now get an intl object in the props of the component. The methods it provides basically correspond to the components we introduced above. At this time we want to display String, you can use the formatMessage method:


const {intl} = this.props;
  
let tmp = intl.formatMessage({id: &#39;intl.name&#39;},{name: &#39;joe&#39;});

The first parameter of formatMessage can be passed in Id, the second parameter can be passed in values, and more For detailed information, please check API

Related recommendations:


Exploring the internal mechanism of React

The way to write components in React is What

React event system knowledge

The above is the detailed content of Examples to explain React-intl implementation of multi-language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn