如何限制 Material UI 实验室自动完成组件中可以选择的最大选项数

doc*_*cid 6 autocomplete reactjs material-design material-ui

(例如)我希望限制用户在我的自动完成组件中仅选择 3 个选项,并在 TAG 数组的长度达到 3 时禁用这些选项。问题是 api 中没有 limitMaxNumberOfTags 选项,我无法找到任何方法访问 Selected 标签数组{除了 limitTags,它只限制可见标签}。类似的事情可能会有所帮助 getOptionDisabled={(options, tags) => (tags.length > 3 ? true : false)} 。这是到目前为止我的自动完成实现

<Autocomplete
  multiple
  id="tags-outlined"
  options={students}
  getOptionLabel={(option) => option.personalInfo.firstName + ' ' + option.personalInfo.lastName}
  defaultValue={[...added]}
  onChange={(e, newVal) => setAdded([...newVal])}
  renderOption={(option, state) => {
    return (
      <Chip
        icon={
          <FaceIcon /> /*<Avatar color="primary" variant='outlined' size="small" className={classes.small}></Avatar>*/
        }
        label={option.personalInfo.firstName + ' ' + option.personalInfo.lastName}
        color="default"
        variant="outlined"
        {...state}
      />
    );
  }}
  renderTags={(options, getTagProps) =>
    options.map((option) => (
      <Chip
        icon={
          <FaceIcon /> /*<Avatar color="primary" variant='outlined' size="small" className={classes.small}></Avatar>*/
        }
        label={option.personalInfo.firstName + ' ' + option.personalInfo.lastName}
        color="primary"
        variant="outlined"
        {...getTagProps({})}
      />
    ))
  }
  filterSelectedOptions
  filterOptions={(options, state) =>
    options.filter((option) => {
      for (let i = 0; i < added.length; i++) {
        if (added[i]._id === option._id) {
          return false;
        }
      }
      return true;
    })
  }
  // --->         getOptionDisabled={(options) => (tags.length > 3 ? true : false)}
  renderInput={(params) => (
    <TextField {...params} variant="outlined" color="primary" label="Select Students" placeholder="Participant" />
  )}
/>
Run Code Online (Sandbox Code Playgroud)

小智 2

最近遇到类似的问题。这就是我最终所做的。基本上,您必须直接在芯片本身上设置禁用标志,因此它会禁用文本输入,但不会禁用芯片。所以你仍然可以删除每个芯片。

export const AutoCompleteWithLimit: React.FC<Props> = ({
  disabled = false,
  limit = 2,
}) => {
  const [disableInput, setDisableInput] = useState<boolean>(
    value.length >= limit
  );

  return (
    <Autocomplete
      // Set disabled based on input
      disabled={disabled || disableInput}
      multiple
      renderTags={(tagValue, getTagProps) =>
        tagValue.map((option, index) => (
          <Chip
            key={index}
            label={option.name}
            {...getTagProps({ index })}
            // Set disable explicitly after getTagProps
            disabled={disabled}
          />
        ))
      }
      onChange={(_event: any, newValue: any[]) => {
        // do something else
        // set the disable input
        setDisableInput(newValue.length >= limit);
      }}
    />
  );
};
Run Code Online (Sandbox Code Playgroud)