带有 Material-ui 没有 autoFocus defaultValue 的文本字段的 React-hook-form 在表单提交期间消失了
React-hook-form with Material-ui textfield without autoFocus defaultValue disappeared during form submit
我在使用 react-hook-form v7 + material-ui 文本字段时遇到问题。如果我设置 autoFocus 或我手动更改文本字段值,则 defaultValue 有效。但是,如果我只是提交而不用鼠标单击非 autoFocus 的字段,则 defaultValue 在表单提交期间消失。请检查 codesandbox link
测试1:什么都不碰,点击提交,你会看到提交的值只有title,没有name和desc
测试2:鼠标点击或修改name的值,提交后会看到name的值存在
我的问题是如何使这个默认值始终提交,即使没有鼠标单击或更改 textField 的值?
请帮助并提前致谢
使用 Material-ui 和 react-hook-form。最好用 Controller
包装它,以允许 react-hook-form 到 link 与第 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.
我在使用 react-hook-form v7 + material-ui 文本字段时遇到问题。如果我设置 autoFocus 或我手动更改文本字段值,则 defaultValue 有效。但是,如果我只是提交而不用鼠标单击非 autoFocus 的字段,则 defaultValue 在表单提交期间消失。请检查 codesandbox link
测试1:什么都不碰,点击提交,你会看到提交的值只有title,没有name和desc
测试2:鼠标点击或修改name的值,提交后会看到name的值存在
我的问题是如何使这个默认值始终提交,即使没有鼠标单击或更改 textField 的值?
请帮助并提前致谢
使用 Material-ui 和 react-hook-form。最好用 Controller
包装它,以允许 react-hook-form 到 link 与第 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.