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
1 Answer
Reset to default 7Yes 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
版权声明:本文标题:javascript - using react-intl to translate a message key outside a component - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744188323a2594398.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论