无法通过React-Hook-Form捕获MUI Joy UI <Select/>组件数据
解决MUI Joy UI Select结合React Hook Form无法捕获数据的问题
你的代码里有两个关键问题导致表单状态始终为null:
- 解构错误:
render参数里的{ field: { onChange, field} }写法有误,你把field对象重复嵌套解构了,导致{...field}实际无法获取到React Hook Form需要的绑定属性,状态自然无法更新。 - 默认值位置错误:
defaultValue应该放在Controller组件上,而非Select内部,因为Controller才是接管表单状态的核心容器。
修复后的代码如下:
<Controller name="category" control={control} rules={{ required: 'Category is required' }} defaultValue="wew" // 将默认值移至Controller render={({ field }) => { // 正确解构field对象 return ( <Tooltip title="Choose a category to help people find you " placement="left" arrow color="info" size="sm" variant="outlined" > <Select {...field} // 直接展开field,自动绑定onChange、value等属性 variant="soft" fullWidth error={Boolean(errors.category)} > <Option value="wew">wew</Option> <Option value="lol">lol</Option> </Select> </Tooltip> ) }} />
补充说明
如果需要自定义onChange逻辑,可以在Select里单独重写,但要记得调用field.onChange同步表单状态:
<Select {...field} onChange={(event, newValue) => { field.onChange(newValue); // 必须调用这个同步React Hook Form状态 // 这里添加你的自定义处理逻辑 }} // 其他属性... />
内容的提问来源于stack exchange,提问作者Richard Pius L. Chua
相关产品推荐
相关产品推荐

