因此,我正在研究需要使用React选择的项目,该项目需要多选。但是,随着选择更多项目,多选示例会不断扩展。如果下拉列表有很多选择可供选择(假设100),则这将不起作用。反应选择库中是否有一种方法可以使该值" xyz& 5又有"或类似的东西?
import React, { Component } from 'react'
import Select from 'react-select'
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
{ value: 'cherry', label: 'Cherry' },
{ value: 'foo', label: 'Foo' },
{ value: 'bar', label: 'Bar' }
]
const MyComponent = () => (
<Select
options={options}
isMulti
className="basic-multi-select"
classNamePrefix="select"
/>
)
您可以使用组件框架覆盖ValueContainer
组件,该组件以其徽章形式保存所选值。
const ValueContainer = ({ children, getValue, ...props }) => {
var values = getValue();
var valueLabel = "";
if (values.length > 0) valueLabel += props.selectProps.getOptionLabel(values[0]);
if (values.length > 1) valueLabel += ` & ${values.length - 1} more`;
// Keep standard placeholder and input from react-select
var childsToRender = React.Children.toArray(children).filter((child) => ['Input', 'DummyInput', 'Placeholder'].indexOf(child.type.name) >= 0);
return (
<components.ValueContainer {...props}>
{!props.selectProps.inputValue && valueLabel }
{ childsToRender }
</components.ValueContainer>
);
};
<Select
{ ... }
isMulti
components={{
ValueContainer
}}
hideSelectedOptions={false}
/>
注意Input
(或DummyInput
)组件的过滤和包含:如果没有Select
组件的基本功能(例如焦点等),则会丢失。还将hideSelectedOptions
Prop设置为false
,以便取消选定选项。
可以在此处查看一个功能的示例。