react中常量文件的翻译

mar*_*339 3 javascript translation internationalization reactjs react-intl

我正在尝试为我的 React 应用程序找到最佳的翻译概念。

我有一个用于翻译的高阶组件,并通过以下方式使用它:

export default translate('MyComponent')(MyComponent);
Run Code Online (Sandbox Code Playgroud)

在一个组件中,我拥有 props 可用的所有文本 - 它对我来说很好用。

但是,我有很多带有常量的纯 javascript 文件,并且还需要在那里进行翻译。例如,有带有错误消息的验证模式或带有选择元素的常量,例如:

export default [
    {
        value: 'aaa',
        label: 'bbb', // want to translate this label
    }
];
Run Code Online (Sandbox Code Playgroud)

在 React 应用程序中翻译纯 js 文件的最佳方法是什么?

jam*_*uhl 7

看起来您使用 i18next(翻译 hoc)。

只需在文件上导入 i18next 并直接使用 t :

import i18next from 'i18next';
export default {
    error: {
        value: 'aaa',
        label: i18next.t('yourKey'), // want to translate this label
    }
};
Run Code Online (Sandbox Code Playgroud)

但更好的是在组件内部进行翻译 - 因此翻译可以适应语言变化。所以我考虑做蔡斯建议的最佳选择:

export default {
    error: {
        value: 'aaa',
        key: 'bbb', // use it as key for t call
    }
};
Run Code Online (Sandbox Code Playgroud)

成分

import Constants from './Constants.js';
const { error } = Constants;

...


render(){
    const { t } = this.props;
    return <span>{${t(error.key)}}</span>
}
Run Code Online (Sandbox Code Playgroud)


Cha*_*nda 0

我对这个问题有点困惑,但是这样的东西有用吗?

常量.js

export default {
    error: {
        value: 'aaa',
        label: 'bbb', // want to translate this label
    }
};
Run Code Online (Sandbox Code Playgroud)

然后在组件中你可以像这样解构它

import Constants from './Constants.js';
const { error } = Constants;
...
render(){
    return <span>{`Error: ${error.label}`}</span>
}
Run Code Online (Sandbox Code Playgroud)

假设只有一个错误容器,如您提供的示例。