[note] React Hook From
react-hook-form @ official website
使用前須知
- 把
useForm
當成useState
來思考,所有表單的狀態都會被「保留」在這個 component 內,並且用類似 controlled component 的方式把值帶入 input 欄位中 - 如果有用到 conditional form,務必要把 reconciliation 處理好,讓 React 能知道這兩個 input 是不同的,否則會造成錯誤(可以透過
key
或 conditional returnnull
,參考這篇:React reconciliation: how it works and why should we care) - 如果希望網頁上沒看到這個 input 時,就把對應的欄位和資料都清除的話(更類似 uncontrolled component),則把
shouldUnregister
設為true
(預設是false
,即使 input 被移除,該 input value 仍然會保留在 react hook form 中)。
Nested Object Fields
Nested Object Fields with react-hook-form @ pjchender gist
react-hook-form 有支援使用 nested object fields,只需要使用 .
(dot syntax)就可以了。有幾點需要留意:
- 在 react-hook-form devTools 的 v3.0.0 中,nested object field 的
Touched
和Dirty
欄位在 devtools 中有問題,不會正確顯示,但實際上的 form 是有作用的。 - 如果有搭配 Yup 使用,記得 validation 時,也要把改 object 包在對應的 object field 中。