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

如何在MUI Select中实现选中禁用其他选项及下拉联动筛选功能

实现级联下拉动态过滤选项方案

核心逻辑

  • 基于选中的校区值,动态过滤年级选项数组
  • 切换校区时自动重置不符合规则的已选年级值,避免表单异常

具体实现步骤

第一步:定义过滤后的年级数组

在函数组件内部直接声明计算属性,类组件则放到render方法中定义即可:

// 动态过滤年级列表
const filteredGrados = colegio === "Academia Internacional David" 
  ? grados.filter(item => {
      // 提取年级数值,学前阶段无数字默认返回0,全部保留
      const gradeNum = parseInt(item.value.match(/\d+/)?.[0] || 0);
      // 只保留6年级及以下的选项
      return gradeNum <= 6;
    })
  // 选中另一个校区时返回全量年级选项
  : grados;

第二步:修改校区切换回调函数,增加异常值重置逻辑

避免切换到「Academia Internacional David」校区时,已选的7年级及以上值不在可选列表中导致的表单异常:

const handleChangeColegio = (e) => {
  const newColegio = e.target.value;
  setColegio(newColegio);
  // 切换到David校区时,校验已选年级是否符合要求
  if (newColegio === "Academia Internacional David") {
    const currentGradoNum = parseInt(grado.match(/\d+/)?.[0] || 0);
    if (currentGradoNum > 6) {
      // 可根据需求改为默认选中的低年级值,比如"Prekínder-3"
      setGrado("");
    }
  }
}

第三步:修改年级下拉框的渲染数据源

将原来全量的grados.map替换为过滤后的filteredGrados.map即可:

<TextField 
     select
     margin="normal"
     value={grado}
     helperText="Seleccione el grado"
     onChange={handleChangeGrado}
>
     {filteredGrados.map((option) => (
        <MenuItem key={option.value} value={option.value}>
          {option.label}
        </MenuItem>
      ))}
</TextField>

内容的提问来源于stack exchange,提问作者React Enjoyer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:45:05