使用父组件 ref 调用挂载 react-redux 的子组件的方法

42 阅读1分钟

为什么使用connect(mapState, mapDispatch)(ChildComponent)挂载redux的子组件,父组件不能通过ref = this.refComp = ref 的方式,让父组件调用子组件的方法

方式说明
forwardRef + connect + useImperativeHandle需要你显式透传 ref,很适合函数组件
父组件 connect,子组件保持纯净更好的架构设计和解耦
  1. forwardRef + connect + useImperativeHandle
    // 子组件文件 ExtractionOptionsProps.js
     import React, { forwardRef, useImperativeHandle, useRef } from 'react';
     
     const ExtractionOptionsProps = forwardRef((props, ref) => {
       const innerRef = useRef();
     
       // useImperativeHandle 暴露父组件想用的方法
       useImperativeHandle(ref, () => ({
         someMethod: () => {
           console.log('子组件方法被调用');
         }
       }));
     
       return (
         <div ref={innerRef}>
           子组件内容
         </div>
       );
     });
     
     const mapState = state => ({});
     const mapDispatch = dispatch => ({});
     
     export default connect(mapState, mapDispatch, null, { forwardRef: true })(ChildComponent);
    
  2. 直接不要让子组件 connect,而是由父组件把 state 和 dispatch 作为 props 传给子组件