从 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.