【问题标题】:How to define a max limit of options in react-select?如何在 react-select 中定义选项的最大限制?
【发布时间】:2021-11-22 01:27:37
【问题描述】:

我为我的应用程序 react 创建了一个 react 选择组件,我有 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}
    />
  );
}

【问题讨论】:

  • 看到多个答案here 也可能对您有所帮助。

标签: reactjs react-select


【解决方案1】:

您可以根据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"
  />
);

现场演示

【讨论】:

  • 非常感谢,如果我可以问,我喜欢你的演示中的选项变成灰色,看起来像禁用,我该怎么做?
  • @Drsaud 我刚刚从官方文档here 分叉了代码框,我认为这是react-select 的默认样式(没有改变任何东西)。
【解决方案2】:

这可能会有所帮助:

const MultiSelect = ({valueList, onChange, options, maxLimit = 5}) => {
  return (
    <Select
      value={valueList}
      isMulti
      onChange={onChange}
      options={options}
      isOptionDisabled={(option) => valueList.length >= maxLimit}
    />
  );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2014-03-11
    相关资源
    最近更新 更多