reactjs - Pass useForm return values from child component to parent - Stack Overflow

In my current project (reactjs + react-hook-form) I have a component Parent that have Child components

In my current project (reactjs + react-hook-form) I have a component Parent that have Child components dynamically generated by a button (add child), each of generated children implements a form using react-hook-form.

Parent is the only one in charge of submitting the forms (and this cannot be changed)so for this I've created a ref in Parent and pass it to every child as prop, in Child I register the handleSubmit function returned by useForm to this ref:

const Parent = () => {
  const childrenRef = useRef(new Map())

const onSave = () => {
  const childrenHandlers = Array.from(childrenRef.current.values())
  const submissionProms = childrenHandlers.map(async (handleSubmit) => {
    return handleSubmit(async (childData) => await callApi(childData))()
  })
  await Promise.all(submissionProms);

}

  return {
    <div>
      <button>Add Child</button>
      <button onClick={() => onSave()}>Save changes</button>
      { 
        childrenFromSomewhere.map(childData => (
          <Child
            childData={childData}
            childrenRef={childrenRef}
          />
        )) 
      }
    </div>
  }
}
const Child = ({childData, childrenRef}) => {
  const { handleSubmit } = useForm(initiaState)

  useEffect(() => {
    childrenRef.current.set(childData.id, handleSubmit)
  }, [])
  
  return <some jsx>
}

This works just fine, only problem is that Parent needs to be aware of modified children and unmodified children so I doesn't make an api call for every child always but only the ones that have changed. So basically I need to pass the isDirty prop from every children along with the handleSubmit function.

And here is when I'm lost, if instead of passing the handleSubmit function a I'm doing now I pass an object with the handleSubmit and the isDirty prop then neither the function nor the isDiry prop keep up to date anymore, that is the handleSubmit function always send default data no matter what, so passing an object as ref doesn't work.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745168326a4614770.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信