Get wrapped component class from connected HOC in react-redux

懵懂的女人 提交于 2021-01-28 06:58:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!