当前,我有以下代码将react-intl暴露给非组件,但是它为intl引发了未定义错误。
我创建了一个单独的组件,称为“ CurrentLocale”,并向其注入了int-intl。导出函数t将使用CurrentLocale上下文中的intl formatMessage。
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 …Run Code Online (Sandbox Code Playgroud) 我正在使用react-intl库进行国际化。在组件内部,我使用injectIntlHOC 来翻译消息键:
import {injectIntl} from 'react-intl';
const Component = props => (
const message = props.intl.formatMessage({id: 'message.key'});
// remainder of component omitted
);
export default injectIntl(Component);
Run Code Online (Sandbox Code Playgroud)
如果我不在组件内,是否可以获得消息翻译?