英文:
React Handle multiple forms within a parent component
问题
我有一个带有动态标签页的页面,每个标签页都有一个表单输入。每个表单都有一个共同的提交按钮。目前,我为每个表单都有一个单独的组件,每个组件都有多个用户输入。
<div id="#parentComponent">
{myForm1 && <div><MyForm1 {...props}/></div>}
{myForm2 && <MyForm2 {...props} />}
<div>
<input type="submit">
</div>
现在,我的问题是在提交时(在父组件中是共同的),我想能够访问每个表单输入的值。但目前,不活动的标签页/组件会被销毁,只有活动的标签页/组件存在于DOM中。
如何处理这种情况的最佳方法是什么?另外,在处理这种情况时,应该有受控/不受控组件的偏好吗?
目前,我正在使用未受控表单来处理这些表单输入(使用useFormContext)。
英文:
I have a page with dynamic tabs and each of them have a form input. There is a common Submit for each of these forms. As of now, I have a separate component for each of the forms and each of them have multiple user inputs.
<div id="#parentComponent">
{myForm1 && <div><MyForm1 {...props}/></div>}
{myForm2 && <MyForm2 {...props} /></div>}
<div>
<input type="submit">
Now, my question is on Submit (common and in the parent component), I want to be able to access each of the form input values. But as of now, my inactive tab/component gets destroyed and only the active tab/component is there in the DOM.
What is the best way to handle this? Also should there be any preference to controlled/uncontrolled components to handle this use case ?
As of now, I am using the uncontrolled form for these form inputs (using the useformcontext)
答案1
得分: 2
我会将状态保存在一个高阶组件中,并在表单内的任何更改时更新它。我会将一个setFormsData
函数传递给每个表单,并在每次更改时添加它们的数据,保留旧状态,就像这样:
const handleOnChange = value => setFormsData(oldFormData => ({...oldFormData, ...value}))
如果愿意的话,也可以使用Redux存储。
英文:
I would keep the state in a higher order component, and update it by any change withing the forms.
I would pass down a setFormsData function to every form, and add their data on every change, keeping the old state, like this:
const handleOnChange = value => setFormsData(oldFormData => {...oldFormData, ...value})
You can also use a redux store if you wish.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论