React (multi-language) is used in the project of the company. Now we need to add multi-language, so WE searched a lot of posts on the Internet and looked at the official website, and finally figured out how to use it, which is recorded here.

Installation:

npm install react-intl --save 
npm install react-router-dom --save-dev
Copy the code

Load environment – data

import { BrowserRouter as Router } from 'react-router-dom' import ToggleList from './common/ToggleList' import {IntlProvider, addLocaleData , FormattedMessage} from 'react-intl'; import en from 'react-intl/locale-data/en'; import zh from 'react-intl/locale-data/zh'; import zh_CN from '.. /locales/zh-CN'; import en_US from '.. /locales/en-US'; addLocaleData([...en, ...zh]);Copy the code

Language conversion directory

Zh-cn file (LANGUAGE content Json file)

En-us file (language content Json file)

※ The language is switched by the lang property in this.state

Render the code

Events connected via this.languageList

Import {FormattedMessage} from ‘react-intl’;

Add variables to the text

Import {IntlProvider, addLocaleData, FormattedMessage} from 'react-intl'; import { BrowserRouter as Router } from 'react-router-dom' <IntlProvider locale={this.state.lang} messages={messages[this.state.lang]}> <Router> <FormattedMessage id="tit" /> </Router> </IntlProvider>Copy the code