2016-03-03 78 views
8

我有反应路由器的应用程序,并想添加国际化。 In react-intl example包裹在IntlProvider中的根组件:React-intl多语言应用程序:改变语言和翻译存储

ReactDOM.render(
<IntlProvider locale="en"> 
    <App /> 
</IntlProvider>, 
document.getElementById('container') 

);

但是只有一个区域设置。如何更新应用程序以添加其他语言,以及如何存储翻译的最佳方式?

回答

7

我都面临着同样的问题,这是我发现:

要改变我以前的解决方案提供here,基本上是结合IntlProvider与连接功能ReduxStore语言。另外不要忘记在语言改变时加入关键字来重新渲染组件。这基本上是所有代码:

这是ConnectedIntlProvider.js,只是结合默认IntlProvider(请注意,在GitHub上的原有注释缺少的关键道具)

import { connect } from 'react-redux'; 
import { IntlProvider } from 'react-intl'; 

// This function will map the current redux state to the props for the component that it is "connected" to. 
// When the state of the redux store changes, this function will be called, if the props that come out of 
// this function are different, then the component that is wrapped is re-rendered. 
function mapStateToProps(state) { 
    const { lang, messages } = state.locales; 
    return { locale: lang, key: lang, messages }; 
} 

export default connect(mapStateToProps)(IntlProvider); 

,然后在入口点文件:

// index.js (your top-level file) 

import ConnectedIntlProvider from 'ConnectedIntlProvider'; 

const store = applyMiddleware(thunkMiddleware)(createStore)(reducers); 

ReactDOM.render((
    <Provider store={store}> 
    <ConnectedIntlProvider> 
     <Router history={createHistory()}>{routes}</Router> 
    </ConnectedIntlProvider> 
    </Provider> 
), document.getElementById(APP_DOM_CONTAINER)); 

接下来要做的就是实施reducer来管理区域设置,并让动作创建者根据需要更改语言。

至于存储翻译的最佳方式 - 我发现了很多关于这个主题的讨论,并且情况似乎很混乱,老实说,我非常困惑,react-intl的制作者非常关注日期和数字格式,而忘记了翻译。所以,我不知道处理它的绝对正确的方式,但这是我做的:

创建文件夹“locales”并在里面创建一堆文件,如“en.js”,“fi.js”, “ru.js”等。基本上你使用的所有语言。
在像这样的翻译的每一个文件输出JSON对象:

export const ENGLISH_STATE = { 
    lang: 'en', 
    messages: { 
     'app.header.title': 'Awesome site', 
     'app.header.subtitle': 'check it out', 
     'app.header.about': 'About', 
     'app.header.services': 'services', 
     'app.header.shipping': 'Shipping & Payment', 
    } 
} 

其他文件具有完全相同的结构,但内部已翻译的字符串。
然后在负责语言改变的Reducer中,一旦发出更改语言的操作,就从这些文件中导入所有状态并将它们加载到redux存储中。在上一步中创建的组件会将更改传播到IntlProvider,并且会发生新的区域设置。使用<FormattedMessage>intl.formatMessage({id: 'app.header.title'})}在页面上输出它,在他们的github wiki上阅读更多内容。
他们有一些DefineMessage函数,但老实说,我找不到任何好的信息如何使用它,基本上你可以忘记它,并确定。

+0

在mobx中,您可以使用https://github.com/Sqooba/mobx-react-intl –