我正在尝试为我的 React 应用找到最佳的翻译概念。
我有一个用于翻译的高阶组件,并通过以下方式使用它:
export default translate('MyComponent')(MyComponent);
在一个组件中,我有所有可用的文本——它对我来说很好。
但是,我有很多带有常量的纯 javascript 文件,也需要在那里进行翻译。例如,有带有错误消息的验证模式或带有选择元素的常量,例如:
export default [
{
value: 'aaa',
label: 'bbb', // want to translate this label
}
];
在 React 应用程序中翻译纯 js 文件的最佳方法是什么?
最佳答案
看起来您使用的是 i18next(临时翻译)。
只需在文件上导入 i18next 并直接使用 t:
import i18next from 'i18next';
export default {
error: {
value: 'aaa',
label: i18next.t('yourKey'), // want to translate this label
}
};
但更好的做法是在组件内部进行翻译——这样翻译就可以适应语言的变化。所以我考虑按照 Chase 的建议做最好的选择:
export default {
error: {
value: 'aaa',
key: 'bbb', // use it as key for t call
}
};
组件
import Constants from './Constants.js';
const { error } = Constants;
...
render(){
const { t } = this.props;
return <span>{${t(error.key)}}</span>
}
关于javascript - React 中常量文件的翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44518857/