目錄
useFormContext是甚麼
useFormContext可以讓你在一些結構比較深的地方取得form的context
,可以把它想成useForm+useContext
可用於多頁
面共用
一個表單
的情境
useFormContext用法
- 準備表單組件、頁面組件
在頁面組件引入useForm、FormProvider,並將useForm的回傳值當作props傳給FormProvider
const formMethods = useForm(); <FormProvider {...formMethods} />
在表單組件引入並呼叫useFormContext,如此就能取得從頁面組件中傳入的方法了
const {register} = useFormContext(); <TextField fullWidth label="User Name" InputLabelProps={{ shrink: true }} {...register("userName")} />
useFormState是甚麼
useFormState的回傳值和formState一樣都可以取得表單狀態的資訊
但根據官方文件,兩者的差異在使用useFormState可以減少re-render
This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level.
It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm.
Using this hook can reduce the re-render impact on large and complex form application.
useWatch和watch之間的差異也一樣
useFormState和useWatch用法
設置defaultValues給useForm
沒有設置defaultValues的話watch或者useWatch無法生效const {register} = useForm<Product>({ defaultValues: { product: "apple", unitPrice: 20, quantity: 10 } });
傳control給hook,如果有用到useFormContext的話則不必
const {register, control} = useForm<Product>({ defaultValues: { product: "apple", unitPrice: 20, quantity: 10 } }); const { isDirty } = useFormState({ control }); const [unitPrice, quantity] = useWatch({ name:['unitPrice', 'quantity'] control }); return ( // 略 <p>total: {unitPrice * quantity}</p> <Button disabled={!isDirty}></Button> );
codesandbox - useFormState & useWatch
參考資料
react-hook-form - useFormContext
react-hook-form - useFormState
react-hook-form
Why useFormState vs formState?
react-hook-form - useWatch example