公司項目使用react(多語言),如今須要添加多語言,因而上網上搜了不少帖子和看了下官網,最終弄明白了使用方法,在這裏記載一下.react
npm install react-intl --save
npm install react-router-dom --save-dev
複製代碼
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]);
複製代碼
※語言經過this.state中得lang屬性切換npm
首先引入
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>
複製代碼