5

父组件

import Child from 'component/Child'

 const dataobj = {
     pdata1: 1,
     pdate2:2
}
 const [dataobj ,setDataobj ] = useState({});
 const pchildref = useRef();
 function parantHandler() {
    // 子组件调用的父组件方法
}
 function parentDivClick() {
    // 父组件调用子组件方法
    pchildref .current._childFn();
}
 return (
    <div>
        <Child 
             ref={pchildref}
             params1={dataobj.pdata1}
             params2={dataobj.pdata2}
             handlerClick={parantHandler}>
        </Child>
        <div onClick={parentDivClick}></div>
    </div>
)

子组件

 const Child = (props,ref) => {   
    // 接收父组件的传值
     const { params1,params2,handlerClick} = props;
     const childRef = useRef();
    // 暴露的子组件方法,给父组件调用
    useImperativeHandle(ref,() => {
         return {
            _childFn() {
                // something….
            }
        }
    })
    // handlerClick子组件调用父组件方法
     return <div 
        ref={childRef} onClick={handlerClick}>
        </div>
}
// forwardRef 配合useRef 父组件调用子组件方法使用
export default forwardRef(Child);

umi3中connect和forwardRef

父组件调用自组件时,子组件需要forwardRef包裹,在子组件中:

const Child = (props) => {   
    // 接收父组件的传值
     const { params1,params2,handlerClick,refInstance} = props;
     const childRef = useRef();
    // 暴露的子组件方法,给父组件调用
    useImperativeHandle(refInstance,() => {
         return {
            _childFn() {
                // something….
            }
        }
    })
    // handlerClick子组件调用父组件方法
     return <div 
        ref={childRef} onClick={handlerClick}>
        </div>
}
const TFunction = connect(({ home }: any) => (home))(Child);
export default forwardRef((props, ref) => <TFunction {...props} refInstance={ref} />);

Judian
16 声望3 粉丝