During react development, it is necessary to call the method of the child component in the parent component. The child component uses Redux’s connect method to wrap a layer into HOC, so the parent component cannot obtain the ref of the child component.
Example code is as follows:
// father comp
const FatherComp = () = > {
const childRef = useRef(null);
useEffect(() = >{
console.log(childRef.current)
},[])
return <ChildComp ref={childRef} />;
};
// child comp
const ChildComp = (props, ref) = > {
useImperativeHandle(ref, () = > ({
hello: () = > console.log('hello world! '),})); };// Unfetchable condition
export default connect(mapStateToProps)(forwardRef(ChildComp));
// Change to:
// function connect(mapStateToProps? , mapDispatchToProps? , mergeProps? , options?)
export default connect(mapStateToProps, null.null, { forwardRef: true })(
forwardRef(ChildComp),
);
Copy the code
The {forwardRef: true} role in the redux source code exposes a ref forward inside the connect component
/**
* If true, use React's forwardRef to expose a ref of the wrapped component
*
* @default false* /forwardRef? :boolean | undefined;
Copy the code