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

MUI NativeSelect结合React Hook Form无法触发表单提交求助

解决MUI NativeSelect配合react-hook-form自动提交失效问题

问题原因

你通过watch全局监听表单变化时,仅允许"change"类型的事件触发提交,但MUI NativeSelect(或native=true的Select)触发的watch事件类型并非"change",导致提交逻辑被过滤拦截。

解决方案

方案1:调整watch的事件类型判断

先打印事件类型确认NativeSelect触发的type值,再修改判断逻辑适配:

const onSubmit = (data: UpdateProspectNeufType) => console.log(data);

useEffect(() => {
    const subscription = watch((_value, {name, type}) => {
        // 先打印type,确认NativeSelect触发的事件类型
        console.log("触发的事件类型:", type);
        // 根据实际type值调整判断,比如如果是"native"则放行
        if ((type !== "change" && type !== "native") || name === undefined) return;
        handleSubmit(onSubmit)();
    });
    return () => subscription.unsubscribe()
}, [handleSubmit, watch]);

方案2:单独监听目标字段变化(更稳定可靠)

放弃全局监听,直接监听typeMaison字段的数值变化,只要值发生改变就触发提交:

const onSubmit = (data: UpdateProspectNeufType) => console.log(data);
// 单独监听typeMaison字段的当前值
const typeMaisonValue = watch("typeMaison");

useEffect(() => {
    // 根据你的defaultValue为null,确保字段有值时再提交
    if (typeMaisonValue !== null) {
        handleSubmit(onSubmit)();
    }
}, [typeMaisonValue, handleSubmit]);

简化NativeSelect的写法

你的Controller中NativeSelect的写法可以简化({...field}已包含value属性,无需重复赋值):

<Controller
    control={control}
    defaultValue={null}
    name={"typeMaison"}
    render={({field}) => (
        <NativeSelect 
            {...field} 
            id={"typeMaison"} 
            onChange={e => field.onChange(e.target.value)}
        >
            {typesMaison.map((typeMaison) => (
                <option key={typeMaison.id} value={typeMaison.id}>{typeMaison.libelle}</option>
            ))}
        </NativeSelect>
    )}
/>

内容的提问来源于stack exchange,提问作者Matteo Casciano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:27:39