【问题标题】:Is it possible to reuse `intl` context from IntlProvider?是否可以从 IntlProvider 重用“intl”上下文?
【发布时间】:2018-01-29 13:39:16
【问题描述】:

我有一个在树(又名门户)之外呈现的组件(弹出窗口),因此丢失了IntlProvider 的上下文:

<IntlProvider locale="en">
    <App />
</IntlProvider>
// * <- renders here

Redux 通过允许将 store 实例作为组件的 prop 传递来解决同样的问题:

import store from "./store";

const Component = () => <Popup store={store} />;

我可以为 ReactIntl​​ 使用类似的方法吗?

【问题讨论】:

  • 您当然可以将intl 对象传递给您的弹出窗口。

标签: javascript reactjs react-intl formatjs


【解决方案1】:

您可以使用injectIntl HOC 将intl 注入到您的组件中。

只需更改您的代码:

const Component = () => <Popup ... />

到:

import { injectIntl  } from 'react-intl';
const Component = ({ intl }) => <Popup intl={intl} />
export default injectIntl(Component)

【讨论】:

  • 我认为要使injectIntl 工作,导出的组件仍需要位于IntlProvider 下的组件层次结构中。
【解决方案2】:

如果你不想将你的组件包装到 HOC 中,useIntl hook 也不错:)

【讨论】:

  • 虽然您在某种程度上回答了这个问题,但您应该在答案中添加工作代码示例。阅读How to write an answer!?
猜你喜欢
  • 1970-01-01
  • 2017-10-30
  • 2011-08-18
  • 2015-10-11
  • 2011-08-24
  • 2019-12-25
  • 1970-01-01
  • 2017-04-19
  • 2014-03-18
相关资源
最近更新 更多