12

反応ルーター アプリがあり、i18n を追加したいと考えています。React -intl のでは、IntlProvider にラップされたルート コンポーネント:

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

);

ただし、ロケールは 1 つだけです。他の言語を追加するためにアプリを更新する方法と、翻訳を保存する最良の方法は?

4

2 に答える 2

22

私は同じ問題に直面しましたが、これが私が見つけたものです:

言語を変更するには、ここで提供されているソリューションを使用しました。これは、基本的に IntlProvider を Connect 関数を使用して 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 ));

次に行うことは、ロケールを管理するためのレデューサーを実装し、アクション クリエーターが必要に応じて言語を変更するようにすることです。

翻訳を保存する最良の方法については、このトピックに関する多くの議論があり、状況が非常に混乱しているように見えます。正直なところ、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',
  }
}

他のファイルはまったく同じ構造ですが、内部に翻訳された文字列が含まれています。
次に、言語の変更を担当するレデューサーで、これらのファイルからすべての状態をインポートし、言語を変更するアクションがディスパッチされるとすぐに redux ストアにロードします。前の手順で作成したコンポーネントは、変更を IntlProvider に伝達し、新しいロケールが適用されます。<FormattedMessage>またはを使用してページに出力しintl.formatMessage({id: 'app.header.title'})}ます。詳細については、github wiki を参照してください。
そこにはDefineMessages関数がいくつかありますが、正直なところ、それを使用する方法に関する良い情報は見つかりませんでした.基本的には忘れて大丈夫です.

于 2016-11-15T06:43:26.783 に答える