reactjs 如何在单击外部时关闭我的react-select?

mnemlml8  于 2023-03-12  发布在  React
关注(0)|答案(1)|浏览(163)
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 }时,我的自定义组件不工作,它显示了初始组件

9rnv2umw

9rnv2umw1#

错误消息表明contains()函数对selectRef.current的当前值不可用。如果selectRef.current为null或未定义,或者它不是具有contains()函数的对象,则可能发生这种情况。

const App = () => {
  const selectRef = useRef(null);

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  });

  const handleClickOutside = (event) => {
    if (selectRef.current && typeof selectRef.current.contains === 'function' && !selectRef.current.contains(event.target)) {
      selectRef.current.select.clearValue();
    }
  };

  return (
    <div>
      <Select ref={selectRef} options={options} />
    </div>
  );
};

相关问题