使用react-intl在组件外部翻译消息密钥 [英] using react-intl to translate a message key outside a component

查看:138
本文介绍了使用react-intl在组件外部翻译消息密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-intl 库进行国际化.在组件内部,我使用injectIntl HOC来翻译消息密钥:

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?

推荐答案

是的! 您必须设置应用程序以提供intl对象,以便可以从外部react组件中使用它.在这些情况下,您将必须使用命令式API.您可以执行以下操作:

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.

这篇关于使用react-intl在组件外部翻译消息密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆