我有一个从material UI组件的多选菜单,我需要确保用户只能从该菜单 Select 三个选项,因为我需要发送该值作为props .现在,我应该做些什么来确保这一点?以下是我使用的代码:

<FormControl sx={{ m: 2, width: "100%" }}>
    <InputLabel id="demo-multiple-chip-label">Location</InputLabel>
    <Select
      labelId="demo-multiple-chip-label"
      id="demo-multiple-chip"
      multiple
      value={selectedLocations}
      onChange={handleChange}
      input={<OutlinedInput label="Location" />}
      
      renderValue={(selected) => (
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
          {selected.map((value) => (
            <Chip key={value} label={value} />
          ))}
        </Box>
      )}
      MenuProps={MenuProps}
    >
      {locationList.map((location: string,index: number) => (
        <MenuItem
          key={index}
          value={location}
          style={getStyles(location, selectedLocations, theme2)}
        >
          {location}
        </MenuItem>
      ))}
    </Select>
</FormControl>

我要 Select 的选项将存储在selectedLocations中.现在,我该怎么做才能确保a user can not choose more than three options.

我在任何地方都找不到任何关于这方面的信息,包括MUI文档.

预期结果:仅从列表中 Select 三个选项

Link to how the dropdown looks in general

推荐答案

我认为SelectSelect.MenuProps中没有提供API来限制所选选项的最大数量.

但是,只要达到所选选项的最大数量,就可以禁用未 Select 的选项:

{locationList.map((location: string, index: number) => (
  <MenuItem
    key={index}
    value={location}
    disabled={selectedLocations.length >= 3 && !selectedLocations.includes(location)}
  >
    {location}
  </MenuItem>
))}

Live Demo

Reactjs相关问答推荐

为什么这个'Suspense'子组件在挂起promise解决后会丢失它的状态,而不是呈现?<>

在一个地方调用函数会影响其他地方调用该函数

有没有方法覆盖NextJS 14中的布局?

关于同一位置的不同组件实例的react S规则被视为相同组件

Redux工具包-useSelector如何通过Reducer引用InitialState?

Gitlab CI和VITE环境变量出现问题

如何使用react-router-dom保护嵌套在受保护路由中的嵌套路由?

如何管理组件列表的复杂状态? (Nextjs/ReactJS)

Syncfusion:带有 TabItemsDirective 的选项卡组件不显示任何内容

如何在 React Native 中更新跨屏幕呈现的上下文状态变量?

页面加载时不显示数组中的数据

如何通过 id 从 useSprings 数组中删除元素

添加 React/Redux 组件模板的 VS Code 扩展

在 redux 中分派到另一个减少时状态值不会改变

使用 React.UseEffect 从 api 获取但我的清理返回不起作用

react-markdown 不渲染 Markdown

错误:无效挂钩调用.钩子只能在函数组件的主体内部调用.使用 next/router 时

如何使用 React Router 在 React 中正确同步 useEffect 和 useLocation 挂钩?

模块解析失败:意外令牌 (257:106) 您可能需要适当的加载程序来处理此文件类型

React useEffect hooks return () => cleanup() vs return cleanup