React 处理父组件内的多个表单

huangapple go评论62阅读模式
英文:

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.

&lt;div id=&quot;#parentComponent&quot;&gt;
{myForm1 &amp;&amp; &lt;div&gt;&lt;MyForm1 {...props}/&gt;&lt;/div&gt;}
{myForm2 &amp;&amp; &lt;MyForm2 {...props} /&gt;&lt;/div&gt;}
&lt;div&gt;
&lt;input type=&quot;submit&quot;&gt;

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 =&gt; setFormsData(oldFormData =&gt; {...oldFormData, ...value})

You can also use a redux store if you wish.

huangapple
  • 本文由 发表于 2023年2月10日 12:36:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定