问题描述
我在使用 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}
/>
...
之后,默认值将能够按预期工作。