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

React Hook Form结合Material-UI下拉框缺失name属性问题求助

Fixing the "Missing name attribute" Error with React Hook Form Controller and Material-UI TextField

Let's break down what's causing that error and fix your component step by step:

What's Wrong in Your Current Code

  1. Duplicate & misplaced name prop: You've added name="role" twice – once as a valid prop on <Controller>, but then again as a standalone line inside the Controller's children. That second name="role" is just floating text, not a prop, so it's ignored. Combined with the incorrect inputRef usage, it confuses React Hook Form about the field's identity.
  2. Incorrect use of register with Controller: When using <Controller>, you don't need to pass register via inputRef – the Controller handles registering the field with the control prop and name prop automatically. Using both causes conflicts and breaks the field registration flow.

Corrected Component Code

<Controller
  name="role"
  control={control}
  rules={{ required: true }} // Move your validation rule here
  render={({ field }) => (
    <TextField
      className={classes.textField}
      select
      label="Select Role"
      variant="outlined"
      required
      fullWidth
      {...field} // Spread all necessary field props (name, value, onChange, etc.)
    >
      {roles.map(role => (
        <MenuItem key={role.value} value={role.value}>
          {role.label}
        </MenuItem>
      ))}
    </TextField>
  )}
/>

Key Changes Explained

  • Use render prop instead of as: The render prop gives you explicit access to React Hook Form's field object, which includes name, value, onChange and other critical props. Spreading {...field} onto the TextField ensures all required attributes (including the name the error was complaining about) are passed correctly.
  • Move validation rules to Controller's rules prop: This is the standard place to define validation when using Controller, instead of trying to use register directly.
  • Remove duplicate/misplaced name prop: The only name="role" you need is the one on the <Controller> itself – it gets passed down to the TextField via the field object automatically.
  • Remove inputRef={register(...)}: This was causing conflicts because Controller already manages field registration through the control and name props.

After making these changes, your dropdown should work as expected, the name attribute will be properly set, and the validation error will disappear. You'll be able to access the selected role value through your form's submit handler without any issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:32:48