gpt4 book ai didi

reactjs - React-intl 多语言应用程序 : changing languages and translations storage

转载 作者:行者123 更新时间:2023-12-03 13:17:07 26 4
gpt4 key购买 nike

我有react-router应用程序并且想添加i18n。在react-intl example根组件封装在 IntlProvider 中:

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

);

但只有一种语言环境。如何更新应用程序以添加其他语言以及如何存储翻译的最佳方式?

最佳答案

我也遇到了同样的问题,这就是我发现的:

要更改语言,我使用了提供的解决方案 here ,这基本上是通过 Connect 函数将 IntlProvider 绑定(bind)到 ReduxStore。另外,不要忘记包含在语言更改时重新渲染组件的 key 。这基本上是所有代码:

这是 ConnectedIntlProvider.js,仅绑定(bind)默认的 IntlProvider(注意 github 上原始评论中缺少的关键 prop)

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 上阅读更多相关内容。
他们那里有一些 DefineMessages 函数,但老实说,我找不到任何如何使用它的好信息,基本上你可以忘记它并确定。

关于reactjs - React-intl 多语言应用程序 : changing languages and translations storage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com