reactjs – React-intl定义反应之外的消息

我有utils.js文件.

export function categoryIdToCategoryName(categoryId) {
let name;
switch (categoryId) {
    case constants.RISK_CATEGORY_LOW:
        name = 'low';
        break;
    case constants.RISK_CATEGORY_MEDIUM:
        name = 'medium';
        break;
    case constants.RISK_CATEGORY_HIGH:
        name = 'high';
        break;
    case constants.RISK_CATEGORY_CRITICAL:
        name = 'critical';
        break;
    default:
        console.warn('see: /utils/risk.js', 'categoryIdToCategoryName:', categoryId);
        name = 'unknown';
   }
    return name;
}

我想用https://github.com/yahoo/react-intl翻译这些文本 – [低,中,高,关键].所以我定义了消息

const translations = defineMessages({
riskLow: {
    id: 'utils.risk.low',
    defaultMessage: 'low',
},
riskMedium: {
    id: 'utils.risk.medium',
    defaultMessage: 'medium',
},
riskHigh: {
    id: 'utils.risk.high',
    defaultMessage: 'high',
},
riskCritical: {
    id: 'utils.risk.critical',
    defaultMessage: 'critical',
}
});

现在最后一步是什么?

如何将消息传递回函数?应该有formatMessage函数,但它只在react上下文中.

最佳答案 我认为在你的情况下你想要访问intl对象,但这个文件不是反应组件,对吧?

如果是这种情况,则必须在此文件中创建一个提供程序,类似于index.js文件中可能已有的提供程序.

在你的utils.js文件中你要添加:

import { IntlProvider, addLocaleData } from 'react-intl';
import localeDataEN from 'react-intl/locale-data/en';
import { translations } from '../point-to-your-translation-file';

addLocaleData(localeDataEN);
const locale = 'en'
const messages = //read it from your translated json file
const intlProvider = new IntlProvider({ locale, messages });
const { intl } = intlProvider.getChildContext(); // this is how you get access to the formatMessage function to use i18n for your messages

function categoryIdToCategoryName(categoryId) {
let name;
switch (categoryId) {
    case constants.RISK_CATEGORY_LOW:
        name = intl.formatMessage(formMessages.riskLow);
        break;
    case constants.RISK_CATEGORY_MEDIUM:
        name = intl.formatMessage(formMessages.riskMedium);
        break;
    case constants.RISK_CATEGORY_HIGH:
        name = intl.formatMessage(formMessages.riskHigh);
        break;
    case constants.RISK_CATEGORY_CRITICAL:
        name = intl.formatMessage(formMessages.riskCritical);
        break;
    default:
        console.warn('see: /utils/risk.js', 'categoryIdToCategoryName:', categoryId);
        name = 'unknown';
   }
    return name;
}

您也可以查看以下答案:React-intl for non components

点赞