React Hook Form如何设置日期默认值为空并清空No选项对应字段?
解决方案
1. 修正表单默认值
首先把dryRunDate的默认值改成null,同时修正代码中的语法错误:
const form = useForm<Inputs>({ resolver: zodResolver(formSchemaData), defaultValues: { doesHaveDryRun: "no", dryRunDate: null, // 将默认值设为null而非new Date() dryRunStart: "", dryRunEnd: "", }, });
2. 替换resetField为setValue
resetField会将字段重置为初始默认值,之前默认值是new Date(),所以重置后仍会保留值。改成直接用setValue将字段设为null或空字符串:
const handleClick = () => { form.setValue("dryRunDate", null); form.setValue("dryRunStart", ""); form.setValue("dryRunEnd", ""); };
3. 更优雅的自动处理方式
无需手动绑定点击事件,通过watch监听单选按钮的变化,自动触发字段清空:
import { watch } from 'react-hook-form'; // 在组件内部添加监听逻辑 watch("doesHaveDryRun", (value) => { if (value === "no") { form.setValue("dryRunDate", null); form.setValue("dryRunStart", ""); form.setValue("dryRunEnd", ""); } });
4. 可选:调整Zod Schema适配空字符串
如果需要让dryRunDate接受空字符串(而非仅null),可以修改Schema:
const formSchemaData = z.object({ doesHaveDryRun: z.enum(["yes", "no"], { required_error: "Please select if yes or not" }), dryRunDate: z.union([z.date(), z.string().length(0)]).optional(), // 允许空字符串或日期类型 dryRunStart: z.string().optional(), dryRunEnd: z.string().optional(), });
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

