【问题标题】:React-hook-form with Material-ui textfield without autoFocus defaultValue disappeared during form submitReact-hook-form with Material-ui textfield without autoFocus defaultValue 在表单提交期间消失了
【发布时间】:2021-07-06 03:02:37
【问题描述】:

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

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

  • 测试2:鼠标点击或修改name的值,提交后会看到name的值就在那里

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

请提前帮助和感谢

【问题讨论】:

  • 感谢@micFung 解决方案。这个问题的主要问题是 material-ui 和 react-hook-form 使用不同的键 inputRef 和 ref。有2个解决方案 1.使用react form controller codesandbox.io/s/… 2.手动映射inputRef和ref codesandbox.io/s/…

标签: reactjs typescript material-ui textfield react-hook-form


【解决方案1】:

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

之后,默认值就可以按预期工作了。

这里是codesandbox for demo

【讨论】:

  • 感谢@micFung,这是可行的解决方案。另外,我想知道是否有不使用 Controller 的解决方案?只用注册?
  • 是的,你可以。但是您需要自己显式设置 ref,因为 material-ui 中的输入 ref 被称为 inputRef 而不是 ref 所以 register() 提供的 ref 无法正确映射。
  • 这里是演示的代码框:codesandbox.io/s/…
  • 太棒了,我现在看到了问题。非常感谢。我希望 material-ui 或 react-hook-form 有一天可以使其可计算:-)。很好的答案和解释@micFung
猜你喜欢
  • 2020-06-24
  • 2021-02-23
  • 1970-01-01
  • 2022-01-04
  • 2021-12-16
  • 1970-01-01
  • 2022-08-03
  • 2020-09-29
  • 2016-12-21
相关资源
最近更新 更多