使用MUI Select组件无法设置值,表单提交时显示为空
React MUI Select组件选择后表单提交值为空的解决方案
你的问题根源在于同时使用了react-hook-form的Controller状态和自定义的本地状态,导致两者状态不同步:Controller组件本身会维护表单字段的状态,但你手动覆盖了Select的value为自定义的selectedOption,并且用自定义的handleChangeData替换了field.onChange,这就导致react-hook-form无法感知到Select的选择变化,最终提交时该字段值为空。
下面提供两种可行的解决方式:
方案一:移除自定义状态,直接使用Controller的内置状态
这是最简洁的方式,优先推荐。react-hook-form的Controller已经封装了表单字段的状态管理逻辑,无需额外维护本地状态:
<Controller control={control} name="income_slab" rules={{ required: true }} render={({ field }) => ( <FormControl variant="outlined" className="control_f"> <InputLabel htmlFor="outlined-age-native-simple"> Select Income range </InputLabel> <Select {...field} inputProps={{ // 无需手动设置name,Controller的name属性已对应表单字段名 }} > {incomeSlabList.map((item: any) => ( <MenuItem key={item.data} value={item.data}> {item.name} </MenuItem> ))} </Select> </FormControl> )} />
只需将field直接解构传递给Select,field中已经包含了value、onChange等必要属性,react-hook-form会自动同步表单状态,提交时就能正确获取到选中的值。
方案二:保留自定义状态,同步更新Controller状态
如果确实需要自定义状态做额外逻辑处理,需在自定义的change事件中同时更新本地状态和Controller的表单状态:
const [selectedOption, setSelectedOption] = React.useState(""); <Controller control={control} name="income_slab" rules={{ required: true }} render={({ field }) => { const handleChangeData = (e: any) => { const value = e.target.value; setSelectedOption(value); // 同步更新Controller的表单状态 field.onChange(value); }; return ( <FormControl variant="outlined" className="control_f"> <InputLabel htmlFor="outlined-age-native-simple"> Select Income range </InputLabel> <Select {...field} onChange={handleChangeData} value={selectedOption} inputProps={{ // name: "age", }} > {incomeSlabList.map((item: any) => ( <MenuItem key={item.data} value={item.data}> {item.name} </MenuItem> ))} </Select> </FormControl> ); }} />
核心是在handleChangeData中调用field.onChange,把选中值同步给react-hook-form,确保表单状态和本地状态一致。
注意事项
- Controller的
name属性要和你提交表单时的目标字段名保持一致(这里是income_slab),确保提交时能正确映射字段值。 - 非必要情况下,尽量避免手动覆盖Controller提供的
value和onChange,减少状态冲突的概率。
内容的提问来源于stack exchange,提问作者govind jha
相关产品推荐
相关产品推荐

