其他分享
首页 > 其他分享> > react hooks 使用ref 操作 form 子组件

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>
    )
  }

标签:useRef,const,form,hooks,react,forwardRef,props,组件,ref
来源: https://www.cnblogs.com/ljh--/p/13955425.html