2016-03-03 77 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 –