使用react开发期间需要在父组件中调用子组件的方法,子组件使用了redux 的 connect
方法包了一层成为了HOC,导致父组件无法获取到子组件的ref。
示例代码如下:
// 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!'),
}));
};
// 无法获取的情况
export default connect(mapStateToProps)(forwardRef(ChildComp));
// 需要改成:
// function connect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?)
export default connect(mapStateToProps, null, null, { forwardRef: true })(
forwardRef(ChildComp),
);
其中 {forwardRef: true}
在redux源码中的作用向connect的组件内部暴露出一个ref转发
/**
* If true, use React's forwardRef to expose a ref of the wrapped component
*
* @default false
*/
forwardRef?: boolean | undefined;