从 react-redux 中连接的 HOC 获取封装的组件类

IT技术 reactjs redux react-redux higher-order-components
2021-05-21 15:39:24

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

例如:

class A extends React.Component {}

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

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

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

1个回答

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

this.aConnectedRef = React.createRef();

...

<ConnectedA ref={this.aConnectedRef} />

...

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

包装类本身可用作WrappedComponent属性:

ConnectedA.WrappedComponent === A

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