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

react-hook-form使用Controller时onSubmit提交事件不触发问题求助

问题原因
  • 你重写了Controller提供的onChange回调,仅更新了本地price状态,没有同步值到react-hook-form的表单状态,导致voucherPrice字段一直停留在初始值false,触发required校验拦截,自然不会触发onSubmit回调
  • 你强制将Input的value绑定为本地的price,同时Controller的defaultValue设为了不符合预期的false,两个状态完全独立没有关联,提交时react-hook-form拿不到正确的字段值
修复代码

调整事件回调

修改handlePriceInputChange,同步输入值到react-hook-form:

const handlePriceInputChange = (ev, rhfOnChange) => {
  const inputVal = parseInt(ev.target.value);
  const finalVal = isNaN(inputVal) ? '' : inputVal;
  setPrice(finalVal);
  // 将值同步给react-hook-form管理
  rhfOnChange(finalVal);
};

调整Controller配置

修正Controller的默认值和透传逻辑,避免属性覆盖冲突:

<form onSubmit={handleSubmit(onSubmit)}>
  <Controller
    name="voucherPrice"
    control={control}
    // 初始值和本地price的初始值对齐
    defaultValue={price}
    rules={{ required: true }}
    render={({ field: { onChange, value, ref, ...restField } }) => (
      <Input 
        // 只透传field里除了onChange、value、ref之外的属性,避免覆盖自定义配置
        {...restField} 
        onChange={(ev) => handlePriceInputChange(ev, onChange)} 
        value={price} 
        type="number" 
        innerRef={ref} 
      />
    )}
  />

  <p>{errors.voucherPrice?.message}</p>

  <Button
    variant="contained"
    sx={{ mt: 1, mr: 1 }}
    type="submit"
  >
    {"Continue"}
  </Button>
</form>

修改后输入值会同时同步到本地price和react-hook-form的表单状态,校验通过后点击提交即可正常触发onSubmit,data参数里会携带voucherPrice的输入值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:57:07