如何在 React-Select 中公开所选选项,使其显示“X 选项已选择”,而不是在选择框中显示所选选项?

问题描述 投票:0回答:1

React-select 是一个很棒的工具,但现在我正在努力解决我自己造成的问题(过度销售的问题)。

react select 提供什么:

它列出了选择框中的所有选定选项,随着时间的推移变得混乱。

我想要实现的是:

我想显示“选择了X个选项”。另外,如果反应选择提供管理外部过滤器,那就太好了。否则,我将手动创建一个外部过滤系统。但如果有人可以帮助我“选择 2 个选项”

javascript reactjs react-select
1个回答
0
投票

您可以创建自定义值容器并将其传递给react-select:

import React from 'react';
import Select from 'react-select';

// Sample options for the Select
const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
  // ... add more options
];

// Custom ValueContainer component
const CustomValueContainer = ({ children, ...props }) => {
  const length = props.getValue().length;
  
  // Check if more than one option is selected
  if (length > 1) {
    // Return a custom display
    return (
      <div className="value-container">
        {length} Options Selected
      </div>
    );
  }
  
  // Return default display for other cases
  return (
    <div className="value-container">
      {children}
    </div>
  );
};

function App() {
  return (
    <div className="App">
      <Select
        isMulti
        options={options}
        components={{
          ValueContainer: CustomValueContainer
        }}
      />
    </div>
  );
}

export default App;

这是所有组件的列表:https://react-select.com/components

© www.soinside.com 2019 - 2024. All rights reserved.