首页 > 解决方案 > React-hook-form with Material-ui textfield without autoFocus defaultValue 在表单提交期间消失了

问题描述

我在使用 react-hook-form v7 + material-ui 文本字段时遇到问题。如果我设置 autoFocus 或手动更改文本字段值,则 defaultValue 有效。但是,如果我只是提交而不用鼠标单击不是自动对焦的文件,则在表单提交期间 defaultValue 消失了。请检查代码和框链接

我的问题是如何使这个默认值始终提交,即使没有鼠标点击或更改 textField 的值?

请提前帮助和感谢

标签: reactjstypescriptmaterial-uitextfieldreact-hook-form

解决方案


将 Material-ui 与 react-hook-form 一起使用。最好将它包装起来,Controller以允许 react-hook-form 与 3rd 方库元素链接。

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}
/>
...

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

这是demo的代码框。


推荐阅读