[英]Support callback for changing another field value when using React Hook Form validation
[英]React Hook Form value is not changing when swapping or Deleting Groups
我正在制作一个动态的嵌套表单生成器。
这是我正在处理的当前项目: https://codesandbox.io/s/ava-dynamic-react-hook-form-ivgt40?file=/src/App.js
我遇到的问题是,当我交换或删除组时,组内的值设置不正确。
我相信这是由于 {...register()} 和输入组件上的更改 ref 造成的,但我不确定。
顶部链接项目中的表单 data.js 文件包含我希望呈现的表单结构。
list: {
id,
label,
control: "list" // identifier that this element is a list
creatable: boolean,
items: [
[elements], // group 1
[elements], // group 2
]
}
input: {
id,
label,
control: "input" // identifier that this element is a input
type: "text" // type of input
defaultValue,
rules: {
required: {
value: boolean,
message: string,
}
}
}
您似乎正在混合跟踪 state 的地方。
你基本上有 2 种类型的 state
react-hook-form
中Element.jsx
中通过混合这些,您必须手动确保它们保持同步
当你使用react-hook-form
时。 您将一些 state 管理委托给该挂钩。 他们通过寄存器提供 API 以跟踪表单的字段和值。
Register 将名称作为第一个参数。
这是表单识别字段的唯一句柄。
新名称将是新字段。
你没有保持同步。
改变顺序会做几件事:
elementIdPath
类似于Emailprofile.0.notifications.0.email.0.email-abcd123
Emailprofile.0.notifications.0.email.0.email-abcd123
作为名称传递给寄存器。handleSwapListElements
运行并通过setElementItem
更改元素elementIdPath
更改: Emailprofile.0.notifications.0.email.1.email-abcd123
(通知索引从 0 更改为 1)保持排序顺序和值同步。 你必须自己决定具体怎么做。 任何一个:
react-hook-form
方法手动保持同步。两者都有起伏。
没有索引的动态表单将要求您将所有信息附加到字段本身。 基本上,您会注册一个唯一密钥 (uuid),并自己跟踪 uuid 路径。
IE你注册到属性:
{
"abcd123-value" : "some@email.de",
"abcd123-path" : "Emailprofile.0.notifications.0.email.0.email-abcd123" // this would not be shown to the user, but still exposed to the form, in the submit you would manually combine the information again.
}
react-hook-form
方法手动保持同步。 每当您更改字段name
时,您将获得当前值。 注销旧名称并在新名称上设置值。
react-hook-form
公开了一个钩子方法。
如果由我决定,并查看您的代码。我可能会朝这个方向尝试 go,而不是重构事物以从名称中删除索引。
这个经过修改的沙箱应该可以描绘出画面。 对于基本元素,它还不能正常工作,但是profile.0.notification.0.email
中的节点应该是 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.