using react-intl to translate a message key outside a component

核能气质少年 提交于 2020-03-02 17:14:18

问题


I'm using the react-intl library for internationalization. Inside a component, I use the injectIntl HOC to translate message keys:

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?


回答1:


Yes it is! You have to setup you application to provide the intl object so that you can use it from outside react components. You will have to use the imperative API for these cases. 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.



来源:https://stackoverflow.com/questions/52593175/using-react-intl-to-translate-a-message-key-outside-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!