如何在react-select中定义选项的最大限制?

10

我为我的react应用程序创建了一个react select组件,其中有70多个选项,因此我想定义用户可以选择的选项的最大限制,以便进行良好的处理。你能帮帮我吗?

代码:

export default function ReactSelect(props) {
  const animatedComponents = makeAnimated();
  return (
    <Select
      isMulti="true" // allow to select mutli options
      isRtl="true" // right to left
      name="name" // html name
      options={accountsNames} // options
      className="basic-multi-select"
      classNamePrefix="select"
      isSearchable="true" // searchable for the closest one
      placeholder="اختر اسم الحساب..." // if there is no option selected
      components={animatedComponents}
    />
  );
}

3
在这里看到了多个答案(https://dev59.com/aVMI5IYBdhLWcg3w4Pk_),可能也能帮助您。 - Boudewijn Danser
2个回答

13
您可以通过以下方式控制所选选项的状态并有条件地禁用选项:selectedOptions.length
const [selectedOptions, setSelectedOptions] = React.useState([]);

return (
  <Select
    isMulti
    value={selectedOptions}
    onChange={(o) => setSelectedOptions(o)}
    options={colourOptions}
    // only allow user to choose up to 3 options
    isOptionDisabled={() => selectedOptions.length >= 3}
    className="basic-multi-select"
    classNamePrefix="select"
  />
);

演示

Codesandbox演示


非常感谢,如果我可以问一下,在您的演示中,我喜欢那个看起来像被禁用的选项变灰的选项,我该如何做到这一点? - Drsaud
1
@Drsaud,我刚刚从官方文档这里fork了codesandbox,我认为这是react-select的默认样式(没有更改任何内容)。 - NearHuscarl
2
不要忘记再次添加 option.isDisabled 检查,因为您的示例现在会破坏默认 API。可以像这样使用 isOptionDisabled={option => option.isDisabled || selectedOptions.length >= 3} - Brouwer

3
这可能有所帮助:
const MultiSelect = ({valueList, onChange, options, maxLimit = 5}) => {
  return (
    <Select
      value={valueList}
      isMulti
      onChange={onChange}
      options={options}
      isOptionDisabled={(option) => valueList.length >= maxLimit}
    />
  );
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接