如何解决React-hook-form with Material-ui textfield without autoFocus defaultValue 在表单提交过程中消失
我在使用 react-hook-form v7 + material-ui 文本字段时遇到问题。如果我设置 autoFocus 或我手动更改文本字段值,则 defaultValue 工作。但是,如果我只是在没有鼠标单击的情况下提交不是 autoFocus 的文件,则 defaultValue 在表单提交过程中消失了。请检查codesandbox link
我的问题是如何使这个默认值始终提交,即使没有鼠标点击或更改 textField 的值?
请帮助并提前致谢
解决方法
将 Material-ui 与 react-hook-form 一起使用。最好用 Controller
包裹它,让 react-hook-form 链接到第 3 方库元素。
https://react-hook-form.com/api/usecontroller/controller
用控制器包裹文本字段
const { handleSubmit,control } = useForm();
...
<Controller
render={({ field }) => (
<TextField
autoFocus
margin="dense"
id="title"
label="Title"
type="text"
fullWidth
{...field}
/>
)}
control={control}
name="title"
defaultValue={data.title}
/>
...
之后,默认值将能够按预期工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。