问题
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