React-hook-form with Material-ui textfield without autoFocus defaultValue 在表单提交过程中消失

问题描述

我在使用 react-hook-form v7 + material-ui 文本字段时遇到问题。如果我设置 autoFocus 或我手动更改文本字段值,则 defaultValue 工作。但是,如果我只是在没有鼠标单击的情况下提交不是 autoFocus 的文件,则 defaultValue 在表单提交过程中消失了。请检查codesandbox link

  • 测试 1:不要触摸任何东西,点击提交,你会看到提交值只有标题但缺少名称和描述

    result

  • 测试二:鼠标点击或者修改name的值,提交后可以看到name的值在那里

    enter image description here

我的问题是如何使这个认值始终提交,即使没有鼠标点击或更改 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}
/>
...

之后,默认值将能够按预期工作。

这是codesandbox for demo