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

Mar*_*nen 3 javascript json reactjs react-intl

所以我的 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>
);
Run Code Online (Sandbox Code Playgroud)

并且Root有多个子组件等等。现在我怎样才能在这些子组件中获得所提供的localemessages?我知道我可以将它们作为道具传递给Root,它再次将它们传递下去,但是我的树相当深,维持这个很麻烦。

是否可以访问它locale并直接messages传递给IntlProvider子组件?

Pan*_*olo 5

如此处的文档中所述,您可以使用 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);
Run Code Online (Sandbox Code Playgroud)

除了format*helper 之外,配置道具,包括messageslocale也可以通过相同的组件道具直接在树下访问intl请参阅intlShape此处的类型定义):

const { locale, messages } = this.props.intl;
Run Code Online (Sandbox Code Playgroud)