如何在组件中访问 IntlProvider 的语言环境和消息?

How to access the IntlProvider's locale and messages in a component?

所以我的 index.js 有这样的东西:

import trFi from './translations/fi_FI.json';
import trSv from './translations/sv_SE.json';

ReactDOM.render(
  <IntlProvider
    locale={my_locale}
    messages={{ fi: trFi, sv: trSv }[my_locale]}
  >
      <Root />
  </IntlProvider>
);

并且Root有多个子组件和全部。现在如何在这些子组件中获取提供的 localemessages ?我知道我可以将它们作为 props 传递给 Root,后者又将它们传递下去,但我的树相当深,维护它很麻烦。

是否可以在子组件中直接访问传递给 IntlProviderlocalemessages

in the docs here 所述,您可以使用 HOC(高阶组件)将您的组件包装在需要访问组件树根部 <IntlProvider /> 提供的国际化数据的位置。

此外,您必须使用 <Formatted*> 组件才能实际使用该数据进行显示。

以下是上述文档中的示例:

import React from 'react';
import { injectIntl, FormattedRelative } from 'react-intl';

const PostDate = ({ date, intl }) => (
    <span title={ intl.formatDate(date) }>
        <FormattedRelative value={ date }/>
    </span>
);

PostDate.propTypes = {
    date: PropTypes.any.isRequired,
    intl: intlShape.isRequired,
};

export default injectIntl(PostDate);

除了 format* 助手之外,配置属性,包括 messageslocale 也可以通过相同的组件属性 intl 直接向下访问树( see the type definition intlShape here):

const { locale, messages } = this.props.intl;

当编写 react with hooks 时,您可以使用 useIntl hook 来访问 intl 对象。

import React from 'react'
import {useIntl, FormattedDate} from 'react-intl'

const FunctionComponent: React.FC<{date: number | Date}> = ({date}) => {
  const intl = useIntl()
  return (
    <span title={intl.formatDate(date)}>
      <FormattedDate value={date} />
    </span>
  )
}

export default FunctionComponent

(示例取自 https://formatjs.io/docs/react-intl/api/#useintl-hook,更多信息可在 https://formatjs.io/docs/react-intl/api/#useintl-hook 找到)

是的,这是可能的。像这样导入 useIntl 钩子:

import { useIntl } from 'react-intl'

const MyComponent: = () => {
  const intl = useIntl()
  console.log('What you need is here: ', intl.locale)

  return (
    <>
      ...
    </>
  )
}

export default MyComponent