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.
动态传值
<FormattedMessage
id="intl.name"
values={{name: <b>{name}</b>}}
/>
我们定义 intl.name 的时候模板里用到了{name} ,这个代表我们可以动态传值,我们可以通过FormattedMessage中的 values 属性传一个JSON对象,这是就会动态显示我们的内容了。
6.其它组件用法
Ract-intl 为我们提供了丰富的组件,可以帮我们很好的处理字符串,时间,日期 ,大家可以自己查看 API,如有不明白的地方,我可以留言。
API用法
有时候我们可能需要在代码中动态做 国际化,这就需要动态API 了。下面我简单介绍下怎么用
1.导入 injectIntl
import { injectIntl, FormattedMessage } from 'react-intl';
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
