react-select多选:保留下拉选中项+自定义显示为n个已选中
实现react-select多选模式的两个自定义需求
需求1:阻止选中选项从下拉菜单消失
react-select默认会自动过滤掉已选中的选项,要保留它们,只需重写filterOption函数,让它只根据输入框的搜索内容过滤,忽略选项的选中状态:
const filterOption = ({ option, inputValue }) => { // 仅根据输入值匹配选项名称,不排除已选中项 return option.name.toLowerCase().includes(inputValue.toLowerCase()); };
需求2:替换选中项为“n个已选中”文本
通过自定义ValueContainer组件,替换默认的选中项标签容器,当有选中项时显示统一的数量文本:
import { components } from 'react-select'; const CustomValueContainer = ({ children, ...props }) => { const { selectProps } = props; const selectedCount = selectProps.value?.length || 0; // 有选中项时显示数量文本,否则保留默认输入框 if (selectedCount > 0) { return ( <components.ValueContainer {...props}> <div style={{ padding: '2px 8px' }}> {selectedCount}个已选中 </div> </components.ValueContainer> ); } return <components.ValueContainer {...props}>{children}</components.ValueContainer>; };
完整代码整合
把上述逻辑整合到你的组件中:
import React, { useState } from 'react'; import ReactSelect, { components } from 'react-select'; const YourComponent = () => { const [selectedSystems, setSelectedSystems] = useState(vSystems); // 假设vSystems是你的选项数组 const filterOption = ({ option, inputValue }) => { return option.name.toLowerCase().includes(inputValue.toLowerCase()); }; const CustomValueContainer = ({ children, ...props }) => { const { selectProps } = props; const selectedCount = selectProps.value?.length || 0; if (selectedCount > 0) { return ( <components.ValueContainer {...props}> <div style={{ padding: '2px 8px' }}> {selectedCount}个已选中 </div> </components.ValueContainer> ); } return <components.ValueContainer {...props}>{children}</components.ValueContainer>; }; return ( <ReactSelect isMulti options={vSystems} getOptionLabel={(option) => option.name} getOptionValue={(option) => option.id} defaultValue={vSystems} value={selectedSystems} onChange={(val) => setSelectedSystems(val)} className="my-react-select-container" classNamePrefix="my-react-select" filterOption={filterOption} components={{ ValueContainer: CustomValueContainer }} /> ); }; export default YourComponent;
补充说明
- 自定义
ValueContainer时保留了无选中项的默认渲染逻辑,确保搜索输入框正常可用。 - 下拉菜单中保留的已选中选项,点击后仍可正常触发选中/取消选中的交互。
- 若要调整“n个已选中”文本的样式,可通过自定义className或内联样式修改。
内容的提问来源于stack exchange,提问作者Turqay Umudzade
相关产品推荐
相关产品推荐

