react-select: 禁用下拉列表

react-select: disable dropdown list

有没有办法禁用下拉列表? 我没有找到任何可以帮助我的道具。

特别是,当用户选择了超过 5 个元素时,我想禁用下拉列表。

我创建了 this codesandbox。它实际上不起作用,因为它没有链接到状态:

const limit = 3;
const defaults = [colourOptions[2], colourOptions[3]];

export default () => (
  <Select
    defaultValue={defaults}
    isMulti
    name="colors"
    options={colourOptions}
    className="basic-multi-select"
    classNamePrefix="select"
    isSearchable={defaults.length < limit}
    // disableDropdown={defaults.length > limit} // <-- something like this
  />
)

您可以 'disable/remove' 通过删除组件来下拉菜单;

components={{
    Menu: () => null,               // Remove menu
    MenuList: () => null,           // Remove menu list
    DropdownIndicator: () => null,  // Remove dropdown icon
    IndicatorSeparator: () => null  // Remove separator
}}
<Select
    defaultValue={defaults}
    isMulti
    name="colors"
    options={colourOptions}
    className="basic-multi-select"
    classNamePrefix="select"
    isSearchable={defaults.length < limit}
    components={{
        Menu: () => null,
        MenuList: () => null,
        DropdownIndicator: () => null,
        IndicatorSeparator: () => null
    }}
/>

Updated code-sandbox

Documentation

你可以简单地做到这一点。基本上跟踪已经设置了多少元素。然后 isOptionDisabled from re-select 如果选项长度大于限制则禁用选项:

import React, { useState } from "react";
import Select from "react-select";
import { colourOptions } from "./docs/data";

const limit = 3;
const defaults = [colourOptions[2], colourOptions[3]];
// console.log(defaults);
export default () => {
  const [options, setOptions] = useState(defaults);
  return (
    <Select
      defaultValue={defaults}
      isMulti
      name="colors"
      options={colourOptions}
      onChange={(val) => setOptions(val)}
      className="basic-multi-select"
      classNamePrefix="select"
      isSearchable={defaults.length < limit}
      isOptionDisabled={(option, test) => options.length > limit} // <-- something like this
    />
  );
};


这是演示:https://codesandbox.io/s/relaxed-feistel-w44ns?file=/example.js:0-675