本文介绍了用于非组件的React-intl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我有以下代码将react-intl暴露给非组件,但是对于未定义的intl则会引发错误.

Currently I have the following code to expose react-intl to non-components, but it throws an error for intl as undefined.

我创建了一个单独的组件,称为"CurrentLocale",并向其注入了int-intl.导出函数t将使用CurrentLocale上下文中的intl formatMessage.

I have created a separate component as 'CurrentLocale' and inject-intl to it. The exporting function t will use intl formatMessage from CurrentLocale context.

import React from 'react';
import {injectIntl} from 'react-intl';
import PropTypes from 'prop-types';
import { flow } from 'lodash';

class CurrentLocale extends React.Component {


    constructor(props,context){

        super();
        console.log(context,props);
        console.log(this.formatMessage);
        const { intl } = this.context.intl;//this.props;

        this.formatMessage = intl.formatMessage;
    }

    render() {
        return false;
    }
}
CurrentLocale.contextTypes={
    intl:PropTypes.object,
};


injectIntl(CurrentLocale);

function intl() {
    return new CurrentLocale();
}

function formatMessage(...args) {
    return intl().formatMessage(...args);
}


const t = opts => {
    const id = opts.id;
    const type = opts.type;
    const values = opts.values;
    let t;

    switch (type){

        case 'message':
        default:
            t = formatMessage(id, values);
    }

    return t;
}

export default t;

t在另一个普通的javascript文件中称为

t is called as in another plain javascript file as,

import t from './locale/t';
t( { type: 'message', id:'button.Next'});

以下是错误消息.预先感谢.

Following is the error message.Thanks in advance.

推荐答案

此行:const { intl } = this.context.intl;应该为const { intl } = this.context;

以下是某人做与您几乎完全相同的事情的参考帖子: https://github.com/yahoo/react-intl/issues/983#issuecomment-342314143

Here is a reference post of someone doing almost the exact same thing as you are: https://github.com/yahoo/react-intl/issues/983#issuecomment-342314143

在上面,作者基本上创建了一个单例,该单例被导出,而不是每次都像上面一样创建新实例.这也许也是您要考虑的事情.

In the above the author is creating essentially a singleton that is exported instead of creating a new instance each time like you have above. This might be something you want to consider as well.

这篇关于用于非组件的React-intl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 05:17