admin管理员组

文章数量:1399922

I'm using the react-intl library for internationalization. Inside a ponent, 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 ponent omitted
);

export default injectIntl(Component);

Is it possible to get a message translation if I'm not inside a ponent?

I'm using the react-intl library for internationalization. Inside a ponent, 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 ponent omitted
);

export default injectIntl(Component);

Is it possible to get a message translation if I'm not inside a ponent?

Share Improve this question edited Oct 1, 2018 at 14:48 Dónal asked Oct 1, 2018 at 14:19 DónalDónal 188k177 gold badges585 silver badges844 bronze badges 1
  • Possible duplicate of React-intl define messages outside of react – sergioviniciuss Commented Jul 24, 2019 at 7:03
Add a ment  | 

1 Answer 1

Reset to default 7

Yes it is! You have to setup you application to provide the intl object so that you can use it from outside react ponents. 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 ponentMessage = intl.formatMessage(messages.foo);
);

I've done a different setup for me, but I guess this should work for you.

本文标签: javascriptusing reactintl to translate a message key outside a componentStack Overflow