从 react-redux 中连接的 HOC 获取封装的组件类 [英] Get wrapped component class from connected HOC in react-redux

查看:51
本文介绍了从 react-redux 中连接的 HOC 获取封装的组件类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

react-redux中使用connect函数时,会创建一个高阶组件.从该 HOC 的实例中,可以访问扩展组件的包装实例.然而,是否有可能从 HOC 类中检索包装好的 class ?

When using the connect function in react-redux, a Higher Order Component is created. From an instance of that HOC, one can access the wrapped instance of the extended component. Is it possible, however, to retrieve the wrapped class from the HOC class?

例如:

class A extends React.Component {}

ConnectedA = connect(mapStateToProps, mapDispatch)(A);

ConnectedA.some_static_method_to_get_the_wrapped_class(); // === A

为清楚起见,我没有可用的 ConnectedA 实例.我需要一个静态方法或属性.存在吗?

For the sake of clarity, I do not have an instance of ConnectedA available. I need a static method or property. Does that exist?

推荐答案

可以使用连接组件 getWrappedInstance 方法 结合 withRef 选项来获取包装组件的引用:

It's possible to use connected component getWrappedInstance method in conjunction with withRef option to get a ref of wrapped component:

this.aConnectedRef = React.createRef();

...

<ConnectedA ref={this.aConnectedRef} />

...

// after render
// this.aConnectedRef.current.getWrappedInstance() instanceof A === true

Wrapped 类本身可用作 WrappedComponent 属性:

Wrapped class itself is available as WrappedComponent property:

ConnectedA.WrappedComponent === A

如果需要 A 静态方法,那么可能应该直接使用对 A 类的引用,或者可以将其重构为不需要静态方法.

If A static method is needed then a reference to A class should be likely used directly, or it could be refactored to not require static method.

这篇关于从 react-redux 中连接的 HOC 获取封装的组件类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆