[react]在子组件 connect 的情况下使用 useRef 无法获取子组件实例

763 阅读1分钟

使用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;