我使用React-Redux-i18n绑定库为redux翻译我的React应用程序。 我还想使用React-Router来处理我的路由。
我可以让这个例子正常工作,这是由React-Redux-i18n提供的:
在app.js中:
const translationsObject = {
en: {
application: {
title: 'Awesome app with i18n!',
hello: 'Hello, %{name}!'
},
date: {
long: 'MMMM Do, YYYY'
},
export: 'Export %{count} items',
export_0: 'Nothing to export',
export_1: 'Export %{count} item',
two_lines: 'Line 1<br />Line 2'
},
nl: {
application: {
title: 'Toffe app met i18n!',
hello: 'Hallo, %{name}!'
},
date: {
long: 'D MMMM YYYY'
},
export: 'Exporteer %{count} dingen',
export_0: 'Niks te exporteren',
export_1: 'Exporteer %{count} ding',
two_lines: 'Regel 1<br />Regel 2'
}
};
const store = createStore(
combineReducers({
...reducers,
i18n: i18nReducer
}),
applyMiddleware(thunk)
);
syncTranslationWithStore(store)
store.dispatch(loadTranslations(translationsObject));
store.dispatch(setLocale('nl'));
然后我可以在我的组件中使用以下内容来翻译字符串:
<Translate value="application.title"/>
可以通过将以下内容更改为&#39; nl&#39;到&#39; en&#39;来改变语言:
store.dispatch(setLocale('nl'));
如何让用户更改语言。例如:
<a href="/" onClick={changeLanguage('nl')}>Nl</a>
<a href="/" onClick={changeLanguage('en')}>En</a>
如何在单击不同的语言链接时更改setLocale?
答案 0 :(得分:0)
正如名称react-redux-i18n
所暗示的,它依赖于redux
来处理存储i18n键和值,即它们存储在reducers
中,特别是i18nReducer
,并且可以使用actions
更改该reducer的状态,例如dispatch(setLocale)
。如果您还不熟悉Redux,我建议您了解basics。
要创建更改语言的链接,您基本上需要使用dispatch
处理程序选择的参数找到setLocale
onClick
对redux商店的操作的方法。 Redux通过connecting存储状态和调度方法为您的组件提供了一种非常好的方法。例如:
import React, { Component, PropTypes } from 'react'
import { connect } from 'redux'
import { setLocale } from 'react-redux-i18n
class ChangeLanguageLink extends Component {
constructor(props) {
super(props)
this.changeLanguage = (e) => {
e.preventDefault() // don't navigate
this.props.changeLanguage(this.props.lang)
}
}
render() {
return (
<a href="#" onClick={ this.changeLanguage }>
{ this.props.lang.toUpperCase() }
</a>
)
}
}
ChangeLanguageLink.propTypes = {
lang: PropTypes.string.isRequired
}
// this will make this.props.changeLanguage available
const mapDispatchToProps = dispatch => {
// dispatch the react-redux-i18n setLocale action
const changeLanguage = lang => dispatch(setLocale(lang))
return { changeLanguage }
}
// using connect makes store.dispatch available for mapDispatchToProps
// and makes sure changeLanguage is added to the component props
@connect(null, mapDispatchToProps)
export class ChangeLanguageLinkContainer
extends ChangeLanguageLink {}
然后您可以像这样使用您的语言更改组件:
<ChangeLanguageLink lang="en" />
<ChangeLanguageLink lang="nl" />
<!-- should produce html like this -->
<a href="#">EN</a>
<a href="#">NL</a>
希望这有帮助!