在我的Mobx + React JS应用程序中,我使用了国际化行为。 请参阅以下示例:
import React, { Component } from 'react'
import {
InjectedTranslateProps,
translate
} from 'react-i18next'
import {
IPropsBase,
IStateBase
} from './interfaces'
class HomeClass extends Component<IPropsBase & InjectedTranslateProps, IStateBase> {
render () {
const { t } = this.props
return (
<div>
{t('common:WELCOME')}
{t('common:DESCRIPTION')}
</div>
)
}
}
export const Home = translate()(HomeClass)
我想知道你是否还有其他方法可以做到这一点? 提前谢谢。
答案 0 :(得分:1)
如果您不想使用提供程序或HOC,并且不需要为每个组件设置特定的名称空间,则可以使用可观察的mobx进行语言切换。
只需创建可存储对象 t 的可观察对象,并创建 changeLanguage 函数包装器,即可在其中重新分配 t 函数。
>当mobx对渲染方法中使用的任何可观察到的变化做出反应时,这将触发所有使用 t 函数的组件中的重新渲染。
export let i18n = observable({
t: t
});
export function changeLanguage (lg: string) {
i18next.changeLanguage(lg);
this.i18n.t = i18next.getFixedT(lg, i18nCfg.ns);// getFixedT will return new function t
}