react hooks 使用ref 操作 form 子组件
父组件
import React, { useState, useRef, useEffect, forwardRef } from 'react'
import ModelForm from './ModelFormCopy'
这样写 const ForwardEditInfo = forwardRef(ModelForm)) 如果组件中有 connect 要使用 forwardRef 就会报错
Warning: forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).
改用下面这个
注意:!!这里不在Component上使用ref 换个属性名 不然会导致覆盖
const ForwardEditInfo = (forwardRef((props, ref) => <ModelForm {...props} refInstance={ref} />))
const DrawerEdit = (props)=>{
let addRef = useRef()
const submit=()=>{
// 获取到了
let params = addRef.current.p()
}
return(
<ForwardEditInfo
ref={addRef}
searchMobile={searchMobile}
initialValues={currentItem}
></ForwardEditInfo>
)
}
子组件
const ModelForm=(props)=>{
const editRef = useRef()
useImperativeHandle(props.refInstance, () => ({
p: form.getFieldsValue
}))
return (
<div ref={editRef}>
</div>
)
}