[英]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.