问题描述
是否可以禁用下拉列表? 我找不到任何可以帮助我的道具。
特别是,当用户选择了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
/>
)
解决方法
您可以通过删除组件来“禁用/删除”下拉菜单;
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
}}
/>
,
您可以简单地做到这一点。基本上跟踪已经设置了多少个元素。然后,如果选项长度大于限制,则isOptionDisabled
从重新选择禁用选项中进行>
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