如何在MUI开关中使用React Hook Form 7
P粉231112437
P粉231112437 2023-09-16 19:43:09
0
1
508

当使用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学习者快速成长!