背景
首先项目使用的是react;需要在项目中使用国际化
安装库
1)npm install react-intl --save
2)npm install intl --save
先安装react-intl插件;这个库提供了 React 组件和Api两种方式来格式化日期,数字和字符串等。
注意:为了兼容Safari各个版本,需要同时安装 intl,intl在大部分的『现代』浏览器中是默认自带的,但是Safari和IE11以下的版本就没有了。
添加 locale 配置文件
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;
添加引用
注意:1)messages这里的值是一个对象
需要在整个项目中使用的话。需要在配置路由的外面添加该引用;还需要判断当前浏览器应该返回的默认message
import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import {Route, Switch, Redirect,HashRouter} from 'react-router-dom';
//添加store--redux
import store from './store/index';
//react 国际化
import {IntlProvider,addLocaleData} from 'react-intl';
import zh_CN from 'components/Language/zh_CN';//个人配置
import en_US from 'components/Language/en_US';//个人配置
import intl from 'intl';
import zh from 'react-intl/locale-data/zh';//react-intl语言包
import en from 'react-intl/locale-data/en';//react-intl语言包
addLocaleData([...en, ...zh]);//需要放入本地数据库
/*react-router不存在hashHistory对象,需要通过history导入创建*/
// import {createBrowserHistory} from 'history'
/*如果不适用react-router-dom中的BrowserRouter、HashRouter、 MemoryRouter这三种Router,则需要通过history来创建*/
import App from 'containers/app'
import Home from 'containers/Home'
//获取需要渲染的根元素
let rootElement = document.getElementById('root');
function chooseLocale(){
switch(navigator.language.split('-')[0]){
case 'en':
return en_US;
break;
case 'zh':
return zh_CN;
break;
default:
return en_US;
break;
} }
ReactDOM.render(
<IntlProvider locale={navigator.language} messages={chooseLocale()}>
<Provider store={store}>
<HashRouter>
<Route path="/" render={({history, location}) => (
<App history={history} location={location} >
<Switch>
<Route path="/home" component={Home} />
</Switch>
</App>
)}/>
</HashRouter>
</Provider>
</IntlProvider>
, rootElement);
关于react-intl插件中组件的用法请参考官网API:
https://github.com/yahoo/react-intl/wiki/Components#formattedmessage
https://github.com/yahoo/react-intl/wiki/API
网友评论