reactjs - React-hook-form with Material-ui textfield without autoFocus defaultValue 在表单提交期间消失了
问题描述
我在使用 react-hook-form v7 + material-ui 文本字段时遇到问题。如果我设置 autoFocus 或手动更改文本字段值,则 defaultValue 有效。但是,如果我只是提交而不用鼠标单击不是自动对焦的文件,则在表单提交期间 defaultValue 消失了。请检查代码和框链接
我的问题是如何使这个默认值始终提交,即使没有鼠标点击或更改 textField 的值?
请提前帮助和感谢
解决方案
将 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的代码框。
推荐阅读
- android - Espresso - 如何点击底部导航栏的特定项目
- c++ - 如何通过退出应用程序来结束无限循环
- laravel - 如何在 Laravel mix 中隐藏警告
- javascript - 在 Laravel 或 javascript 中自动上传文件
- angular - Angular 11如何验证confirmPassword与使用反应式表单的密码相同
- android - 找不到符号类 ActivityMainBinding
- python-3.7 - 你能帮我纠正这个错误吗:configparser?
- google-cloud-platform - Cloud SQL HA - 故障回复到哪个区域?
- python - 启动浏览器时 subprocess.call 挂起
- arrays - Mongoose - 更新嵌套数组中的多个字段