问题
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?
E.g.:
class A extends React.Component {}
ConnectedA = connect(mapStateToProps, mapDispatch)(A);
ConnectedA.some_static_method_to_get_the_wrapped_class(); // === A
EDIT: For the sake of clarity, I do not have an instance of ConnectedA
available. I need a static method or property. Does that exist?
回答1:
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 class itself is available as WrappedComponent
property:
ConnectedA.WrappedComponent === 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.
来源:https://stackoverflow.com/questions/52315282/get-wrapped-component-class-from-connected-hoc-in-react-redux