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

React Hook Form结合Material UI TextField表单校验不生效问题求助

问题根因与解决方案

核心问题定位

校验错误不展示、onBlur事件未触发的问题来自三个配置错误:

  1. React Hook Form 提供的field.ref被错误绑定到了Material UI TextField的外层容器节点,没有绑定到实际的input输入框,导致RHF无法监听输入框的失焦事件,isTouched状态始终为false
  2. 未指定useForm的校验触发模式,默认仅在表单提交时触发校验,即使失焦事件正常也不会立刻展示错误
  3. 冗余的innerRef={field.ref}写法干扰了默认的事件绑定逻辑

修复步骤

1. 调整useForm配置,指定校验触发时机

按需选择校验模式,常用可选值:

  • onTouched:输入框失焦后触发校验
  • onChange:输入内容变化时实时触发校验
  • onSubmit:仅提交时触发校验(默认值)
const {
  control,
  formState,
  handleSubmit,
  watch,
} = useForm<NovoSinistroForm>({
  mode: 'onTouched' // 按需求调整模式即可
});

2. 修正Controller内TextField的属性绑定

将field中的ref单独提取,传递给TextField的inputRef属性(指向内部实际输入框),删除冗余的innerRef配置:

<Controller
  name="nomeResponsavelVistoria"
  control={control}
  rules={{
    required:{
      value: true,
      message: "Campo obrigatório."
    }
  }}
  render={({ 
    field: { ref, ...restField },
    fieldState: { invalid, isTouched, error },
  }) => (
    <TextField
      {...restField}
      inputRef={ref}
      label="Responsável por vistoria"
      type="text"
      InputLabelProps={{
        shrink: true,
      }}
      error={invalid && isTouched}
      helperText={invalid && isTouched ? error?.message : undefined}
    />
  )}
/>

修复后效果说明

修改完成后输入框失焦时isTouched会正常更新,校验逻辑会按配置的模式触发,错误提示会正常展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:15:07