【问题标题】:How to access the IntlProvider's locale and messages in a component?如何访问组件中的 IntlProvider 的语言环境和消息?
【发布时间】:2017-08-30 17:50:57
【问题描述】:

所以我的 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?我知道我可以将它们作为道具传递给Root,它再次将它们传递下去,但我的树相当深,维护它很痛苦。

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

【问题讨论】:

    标签: javascript json reactjs react-intl


    【解决方案1】:

    正如in the docs here 所解释的那样,您可以使用 HOC(高阶组件)将组件包装在需要访问组件树根部 &lt;IntlProvider /&gt; 提供的国际化数据的位置。

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

    这是上述文档中的一个示例:

    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* helpers 之外,包括messageslocale 在内的配置道具也可以通过相同的组件道具intl (see the type definition intlShape here) 直接沿树向下访问:

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

    【讨论】:

    • 是的,第一个链接是我最初遵循的,但是这个特殊的用例需要我翻译 &lt;input&gt;placeholder 属性,因此我不能使用 &lt;Formatted*&gt; 组件为此。
    • "如果您需要直接访问,可以从组件的 props 中访问消息本身。此示例中对此进行了说明"我不太关注这里,该示例仅使用全局 @987654335 @ 目的?我特别问是否可以在子组件中获取传递给&lt;IntlProvider&gt;message 对象,或者我唯一的选择是将它作为道具转发到整个树中
    • 哇,是的,我回答得太快了,对不起!我相应地更新了我的答案。
    【解决方案2】:

    使用钩子编写 react 时,您可以使用 useIntl 钩子来访问 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 找到)

    【讨论】:

      【解决方案3】:

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

      import { useIntl } from 'react-intl'
      
      const MyComponent: = () => {
        const intl = useIntl()
        console.log('What you need is here: ', intl.locale)
      
        return (
          <>
            ...
          </>
        )
      }
      
      export default MyComponent
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-21
        • 1970-01-01
        • 2011-05-10
        • 2021-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多