当使用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]);
开关的实现如下:
} label="Profil öffentlich (beinhaltet Vor- und Nachname)" />
这反过来是一个完全正常工作的复选框组件:
} label="Steuerbescheinigung benötigt?" />
如何在MUI开关中使用react-hook-form并设置初始值?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号