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

使用react-hook-form时select组件取值返回undefined如何解决

问题原因及修复方案

核心问题点

  • 字段名大小写不统一,且手动传的name属性覆盖了register返回的绑定属性:你调用register('Category')生成的绑定对象自带name: "Category",但你给Select组件额外传了name="category"(小写),直接覆盖了正确的绑定字段名,同时你watch的字段名和注册的字段名如果不匹配,自然无法拿到对应值
  • 动态生成的<option>未声明value属性,下拉选中后无法正确传递取值
  • 占位用的默认<option>错误添加了selected属性,和react-hook-form的受控逻辑冲突,还多余添加了name属性
  • 错误提示的校验字段名和注册字段名不统一,你注册的是大写Category,但判断的是errors.category(小写),会导致校验提示不生效

修正代码

/src/components/Select.js

import React from 'react'

const Select = ({ options, name, placeholder, ...rest }) => {
   return (
        <div className="mt-4">
            <select 
              name={name}
              {...rest} 
              className="py-2 px-4 w-full dark:bg-theme-dark-gray rounded-sm"
            >
                {/* 移除错误的name属性和selected属性,添加空value */}
                <option value="" disabled>Select {placeholder || name}</option>
                {options}
            </select>
        </div>
    )
}

export default Select

/app.js

const App = () => {
    // 其余代码省略
    // 字段名统一为小写category,和后续错误判断逻辑保持一致
    console.log(watch('category'));
    
    return (
        <Select
            {/* 注册字段名调整为小写,和后续逻辑统一 */}
            {...register('category', {required: true})}
            {/* 移除手动传入的name属性,避免覆盖register返回的绑定name */}
            placeholder="category"
            options= {
                categoryList.map(category => {
                    return (
                        {/* 显式声明value属性 */}
                        <option key={category.id} value={category.category}>{category.category}</option>
                    )
                })
            }
        />
        {
            errors.category &&
            <Error 
                message='category is required'
            />
        }
    )
    // 其余代码省略
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 00:24:05