const Filters= ({ label, placeholder, value, options, onChange}) => {
return (
<FiltersStyled>
<h4>{label}</h4>
<div>
<Select placeholder={placeholder} value={value} onChange={onChange} isClearable={false} options={options} isMulti closeMenuOnSelect={false} noOptionsMessage={() => ''} hideSelectedOptions={false} components={{ ValueContainer }} />
</div>
</FiltersStyled>
)
}
const ValueContainer = ({ hasValue, children, getValue, ...props }) => {
let [values, input] = children;
if (Array.isArray(values)) {
const { length } = values;
if (getValue().length > 0 && getValue().length <= 3) {
values = getValue().map(x => x.label).join(', ')
} else {
const otherCount = length - 3;
values = getValue().slice(0, 3).map(x => x.label).join(', ') + ` + ${otherCount}`
}
}
return (
<Select.components.ValueContainer {...props}>
{values}
{!hasValue && input}
</Select.components.ValueContainer>
);
}
这是我的 react-select 我创建了一个自定义容器,我的问题是当我用自定义容器在外面单击时它不会关闭我的 react-select
当我从
components={{ ValueContainer }}
到 components={ ValueContainer }
时,我的自定义组件不起作用,它向我显示初始组件
您可以通过创建一个 ref 和一个事件监听器来监听菜单外的点击来做到这一点
const App = ()=>{
const selectRef = useRef(null);
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
});
const handleClickOutside = (event) => {
if (selectRef.current && !selectRef.current.contains(event.target)) {
selectRef.current.select.clearValue();
}
};
return (
<div>
<Select ref={selectRef} options={options} />
</div>
);
}