You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-hook-form结合react-datetime点击按钮设当前时间提交取值undefined如何解决

问题原因

你没有将Controller提供的表单状态同步逻辑和Datetime组件绑定,单独维护的currentDateTime状态和react-hook-form的表单状态完全隔离,因此提交表单时读取不到resetDateTime的值。

解决方案

你不需要额外维护独立的时间状态,直接复用react-hook-form内置的状态管理能力即可,修改后的代码如下:

  1. 首先从useForm的返回值中解构出setValue方法,用于手动更新表单字段值:
const { control, handleSubmit, setValue } = useForm({
  // 可按需设置初始值,不需要可忽略
  defaultValues: {
    resetDateTime: null
  }
});
  1. 调整组件绑定逻辑:
<Controller
    name="resetDateTime"
    control={control}
    required
    render={({ field }) => (
        <Datetime
            onChange={(timeVal) => field.onChange(timeVal)}
            inputProps={{
                placeholder: "MM-DD-YYYY HH:mm",
            }}
            value={field.value}
            viewMode="time"
        />
    )}
/>
<Button 
    color="primary" 
    className="ml-1" 
    onClick={() => setValue("resetDateTime", moment())}
>
    Immediate
</Button>

修改后不管是用户手动选择时间,还是点击Immediate按钮,都会直接更新react-hook-form的表单状态,提交表单时即可正常读取到resetDateTime的值。

可选优化:如果你需要提交格式化后的字符串而不是moment对象,可以在Datetime的onChange回调里先做格式转换再传给field.onChange:

onChange={(timeVal) => field.onChange(moment(timeVal).format('MM-DD-YYYY HH:mm'))}

内容的提问来源于stack exchange,提问作者Santhosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:24:05