react中常量文件的翻译 [英] Translations for constants files in react

查看:156
本文介绍了react中常量文件的翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to find best concept of translations for my react app.

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

I have a higher order component for translations and use it by:

export default translate('MyComponent')(MyComponent);

在组件中,我可以通过道具获得所有文本-对我来说很好用.

And inside a component I have all texts available by props - it works fine for me.

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

But, I have a lot of pure javascript files with constants and also need a tranlations there. There is for example validation schema's with error messages or constats with select elements like:

export default [
    {
        value: 'aaa',
        label: 'bbb', // want to translate this label
    }
];

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

What is the best aproch to translate pure js files in react app?

推荐答案

看起来就像您在使用i18next(即席翻译).

looks like you use i18next (translate hoc).

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

Just import i18next on the file and use t directly:

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

但是最好在组件内部进行翻译-因此翻译可以适应语言的变化.因此,我认为执行Chase建议的最佳选择是:

But better would be translating inside the component - so translation can adapt to language change. So i consider doing what Chase suggest would be best option:

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>
}

这篇关于react中常量文件的翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆