React-intl 实现多语言

前言

React 作国际化,我推荐使用 React-intl , 这个库提供了 React 组件和Api两种方式来格式化日期,数字和字符串等。知道这个库了,那让咱们开始使用它react

组件用法

为了和React 比较融和,咱们能够使用组件的方式git

1.安装

npm install react-intl --savegithub

2.添加引用

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

3.添加 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;
4.使用<IntlProvider />

这个组件用于设置 i18n 的上下文,它将包装应用程序的根组件,以便整个应用程序将配置在 i18n 的上下文中.
最主要的两个配置项是: loacle 当前的语言环境 messages 当前语言的内容。
咱们要动态切换语言,须要动态改这两个配置。api

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='zh' messages={zhCN}>
                <Provider store={store}>
                    <Router history={history}>
                    </Router>
                </Provider>
            </IntlProvider>
        )
    }
}
5.使用<FormattedMessage />
基础用法
<FormattedMessage 
  id="intl.hello"
  defaultMessage={'hello'}
/>

若是当前语言环境是 中文,它会显示你好 ,若是是英文环境,会显示Hello.ide

动态传值
<FormattedMessage
    id="intl.name"
    values={{name: <b>{name}</b>}}
/>

咱们定义 intl.name 的时候模板里用到了{name} ,这个表明咱们能够动态传值,咱们能够经过FormattedMessage中的 values 属性传一个JSON对象,这是就会动态显示咱们的内容了。ui

6.其它组件用法

Ract-intl 为咱们提供了丰富的组件,能够帮咱们很好的处理字符串,时间,日期 ,你们能够本身查看 API,若有不明白的地方,我能够留言。this

API用法

有时候咱们可能须要在代码中动态作 国际化,这就须要动态API 了。下面我简单介绍下怎么用code

1.导入 injectIntl

import { injectIntl, FormattedMessage } from 'react-intl';orm

2.在组件中注入

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

我在项目中用到了Redux,注入的时候应该向上面那样,若是你没有用Redux ,只须要 export defuault injectIntl(App)

3.使用 intl 对象

咱们经过第二步的注入,如今在咱们在 组件的 props 上会获得一个 intl 对象,它提供的方法和我们上边介绍的组件基本相对应,这时候咱们想要显示字符串,能够使用formatMessage 方法:

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

formatMessage的第一个参数能够传入Id, 第二个参数传入 values ,更详细的了解,请查看 API

结束语

教程的代码,我已放到github 上,你们若是须要,自行查看 React-intl

相关文章
相关标签/搜索