首页 > 解决方案 > React select - 更改所选值的显示方式

问题描述

我在基于 ReactJs 的应用程序中使用反应选择控件。我将其用作多选控件。但是一旦用户选择了多个值,而不是显示所有选定的值,我想显示第一个选定的值 + N。所以如果选择了两个值,我想说'XYZ'+ 1。如果只有一个值被选中我会说'XYZ'。这是一个工作示例

标签: javascriptreactjsreact-select

解决方案


您需要像下面那样覆盖 ValueContainer。工作沙箱

const ValueContainer = props => {
  let length = props.getValue().length;

  return (
    <components.ValueContainer {...props}>
      {length > 1 ? (
        <>
          {props.children[0][0]}
          {!props.selectProps.menuIsOpen && `${length - 1} Items`}
          {React.cloneElement(props.children[1])}
        </>
      ) : (
        <>{props.children}</>
      )}
    </components.ValueContainer>
  );
};

在选择中,您需要覆盖

<Select
 components={{ValueContainer}}
 hideSelectedOptions={false}
 ...
/>

推荐阅读