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

React Hook Form输入时DevTools中value属性消失问题求助

问题解决:React Hook Form结合自定义MUI TextField时输入后value属性消失

问题根源

React Hook Form的register方法需要获取输入框的DOM元素ref来追踪和管理表单状态。你的自定义MuiTextField组件直接将register返回的props传递给MUI原生TextField,但MUI的TextField组件的ref指向的是组件实例,而非底层的<input> DOM元素,导致React Hook Form无法正确绑定到输入框,输入后就会出现DevTools中value属性消失的情况。

而原生MUI TextField能正常工作,是因为它内部已经处理了ref向底层input元素的传递逻辑。


解决方案

方案1:修改自定义组件,传递inputRef

调整MuiTextField组件,显式接收并传递inputRef到MUI TextField的对应属性,让register返回的ref能直接绑定到底层input元素:

import { TextField } from '@mui/material'

export const MuiTextField = ({
  label,
  type,
  error,
  helperText,
  variant = "outlined",
  color = "primary",
  size = "small",
  inputRef, // 新增inputRef参数
  ...rest
}) => {
  return (
    <TextField
      label={label}
      type={type}
      error={error}
      helperText={helperText}
      variant={variant}
      color={color}
      size={size}
      inputRef={inputRef} // 将inputRef传递给MUI TextField的inputRef属性
      {...rest}
    />
  );
};

修改后,Login组件中原来的register用法无需改动,就能正常追踪表单值,DevTools里的value属性也会持续显示。

方案2:使用React Hook Form的Controller组件

如果不想修改自定义组件,可以用Controller组件包裹MuiTextField,通过受控方式管理表单状态,不需要依赖ref传递:

首先在Login组件中导入Controller:

import { useForm, Controller } from "react-hook-form";

然后替换原来的MuiTextField部分:

<MuiStack mt={2} p={2} >
  <MuiBox flex={1} direction="row">
    <MuiAvatar src={require("./assets/logo.png")} height={100} width={100}/>
  </MuiBox>
  {/* 用Controller包裹邮箱输入框 */}
  <Controller
    name="email"
    control={control}
    rules={{ required: "Email is required" }}
    render={({ field }) => (
      <MuiTextField
        label="Email"
        type="text"
        error={!!errors.email}
        helperText={errors.email?.message}
        {...field}
      />
    )}
  />
  {/* 用Controller包裹密码输入框 */}
  <Controller
    name="password"
    control={control}
    rules={{ required: "Password is required" }}
    render={({ field }) => (
      <MuiTextField
        label="Password"
        type="password"
        error={!!errors.password}
        helperText={errors.password?.message}
        {...field}
      />
    )}
  />
  <MuiButton
    type="submit"
    variant="contained"
    color="primary"
    text="Login"
  />
</MuiStack>

Controller会将表单的value、onChange等属性通过field对象传递给自定义组件,确保React Hook Form能完全控制表单状态,解决value属性消失的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 03:33:30