React select-更改所选值的显示方式

问题描述 投票:1回答:1

我正在基于ReactJs的应用程序中使用react select控件。我将其用作多选控件。但是一旦用户选择了多个值,而不是显示所有选择的值,我想显示第一个选择的值+N。因此,如果选择了两个值,我想说“ XYZ” +1。如果只有一个值选择后,我会说“ XYZ”。这是工作中的example

javascript reactjs react-select
1个回答
0
投票

您需要像下面那样重写ValueContainer。工作sandbox

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}}
 ...
/>
© www.soinside.com 2019 - 2024. All rights reserved.