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

React Hook Forms Controller提交值异常:整合Material UI遇问题

解决React Hook Form + Material UI提交时仅获取默认值的问题

Hey there! Let's fix that frustrating issue where you're only getting default values instead of the actual input content when submitting your form.

问题根源

你的Controller组件的render回调没有把React Hook Form(RHF)提供的状态同步属性传递给自定义的QControl组件。RHF依赖field对象里的value和onChange来追踪输入框的实时变化,缺失这些关联的话,表单状态就会一直停留在初始的默认值上。

修复方案

只需要调整Controller的render部分,把RHF的field属性传递给QControl,让两者状态同步起来:

import { useForm, Controller } from "react-hook-form";
import Button from "@mui/material/Button";
import SaveIcon from "@mui/icons-material/Save";

// 假设你的QControl需要接收value和onChange来同步状态
const QControl = ({ uiProp, context, value, onChange }) => {
  // 确保组件内部使用传入的value,并在内容变化时调用onChange通知外部
  return (
    // 这里替换成你的实际UI实现,比如Material UI的TextField
    <input
      type="text"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      // 应用你的uiProp等自定义属性
    />
  );
};

const YourForm = () => {
  const { control, handleSubmit } = useForm();
  const defaultValue = "你的默认值";
  const name = "targetFieldName";

  const onSubmit = (data) => {
    console.log("提交的真实数据:", data);
  };

  // 用handleSubmit包裹你的提交逻辑,这部分你之前的写法是对的
  const onSubmission = handleSubmit(onSubmit);

  return (
    <>
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        // 关键:接收field参数,把value和onChange传递给QControl
        render={({ field }) => (
          <QControl
            uiProp={uiProp}
            context={context}
            value={field.value}
            onChange={field.onChange}
          />
        )}
      />
      <Button
        type="submit"
        className="form-actions"
        variant="contained"
        color="primary"
        startIcon={<SaveIcon />}
        onClick={onSubmission}
      >
        保存
      </Button>
    </>
  );
};

额外小提示

  • 如果你的QControl是基于Material UI的原生组件(比如TextField),可以直接展开field属性更省事:
    render={({ field }) => <TextField {...field} label="输入内容" />}
    
  • 如果QControl自身维护了内部状态,一定要添加逻辑和传入的value保持同步(比如用useEffect监听value变化更新内部状态)。

这样修改后,RHF就能正确追踪输入框的实时变化,提交时就能拿到你实际输入的值啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:19:39