如何在MUI開關中使用React Hook Form 7
P粉231112437
P粉231112437 2023-09-16 19:43:09
0
1
507

當使用react-hook-form與MUI開關一起使用時,即使將值設為true,開關在頁面載入時也不會顯示初始值。然而,這似乎是一個顯示問題,因為在未觸摸按鈕的情況下提交表單會傳回具有定義為true的值的開關的true。此外,點擊這些按鈕(顯示為false)一次不會產生任何效果(它們仍然停留在左邊),第二次點擊將實際上再次切換它們。

使用hook設定初始值(適用於所有其他欄位類型):

useEffect(() => {
  if (userProfile) {
    setValue('firstname', userProfile.firstname);
    setValue('lastname', userProfile.lastname);
    setValue('show_profile', userProfile.show_profile || false);
  }
}, [userProfile]);

開關的實作如下:

<FormControlLabel
    control={<Switch {...register('show_profile')} />}
    label="Profil öffentlich (beinhaltet Vor- und Nachname)"
/>

這反過來是一個完全正常工作的複選框元件:

<FormControlLabel
    control={
      <Checkbox
        {...register('steuerbescheinigung')}
        name="steuerbescheinigung"
      />
    }
    label="Steuerbescheinigung benötigt?"
  />

如何在MUI開關中使用react-hook-form並設定初始值?

P粉231112437
P粉231112437

全部回覆(1)
P粉933003350

根據文檔

您需要使用react-hook-form中的Controller元件來包裝您的Switch元件,並從欄位物件傳遞valueonChange屬性。

例如:

<Controller
  name="show_profile"
  control={control}
  render={({ field: { onChange, value } }) => (
    <FormControlLabel
      control={<Switch checked={value} onChange={onChange} />}
      label="Profil öffentlich (beinhaltet Vor- und Nachname)"
    />
  )}
/>;

您可以在這裡查看完整的範例。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!