是否可以重用 IntlProvider 中的“intl”上下文?

Is it possible to reuse `intl` context from IntlProvider?

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

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

Redux 通过允许将商店实例作为组件的道具传递来解决同样的问题:

import store from "./store";

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

是否有类似的方法可以用于 ReactIntl​​?

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

只需更改您的代码:

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

至:

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

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