admin管理员组文章数量:1414614
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.
本文标签: reactjsPass useForm return values from child component to parentStack Overflow
版权声明:本文标题:reactjs - Pass useForm return values from child component to parent - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745168326a2645819.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论