简体   繁体   English

使用react-intl在组件外部翻译消息密钥

[英]using react-intl to translate a message key outside a component

I'm using the react-intl library for internationalization. 我正在使用react-intl库进行国际化。 Inside a component, I use the injectIntl HOC to translate message keys: 在组件内部,我使用injectIntl HOC转换消息密钥:

import {injectIntl} from 'react-intl';

const Component = props => (
    const message = props.intl.formatMessage({id: 'message.key'});
    // remainder of component omitted
);

export default injectIntl(Component);

Is it possible to get a message translation if I'm not inside a component? 如果我不在组件内部,是否可以获取消息翻译?

Yes it is! 是的! You have to setup you application to provide the intl object so that you can use it from outside react components. 您必须设置应用程序以提供intl对象,以便可以从外部react组件中使用它。 You will have to use the imperative API for these cases. 在这些情况下,您将必须使用命令式API。 You can do something like this: 您可以执行以下操作:

import { IntlProvider, addLocaleData, defineMessages } from 'react-intl';
import localeDataDE from 'react-intl/locale-data/de';
import localeDataEN from 'react-intl/locale-data/en';
import Locale from '../../../../utils/locale';

addLocaleData([...localeDataEN, ...localeDataDE]);
const locale = Locale.getLocale(); // returns 'en' or 'de' in my case

const intlProvider = new IntlProvider({ locale, messages });
const { intl } = intlProvider.getChildContext();

const messages = defineMessages({
  foo: {
    id: 'bar',
    defaultMessage: 'some label'
  }
});
const Component = () => (
  const componentMessage = intl.formatMessage(messages.foo);
);

I've done a different setup for me, but I guess this should work for you. 我为我做了其他设置,但是我想这应该对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM