繁体   English   中英

如何使用react-select v2渲染所选项目

[英]How to render amount selected items with react-select v2

我正在使用react-select版本2,我无法更改多选的自定义行为。 我想显示所选项目的数量而不是所选项目的列表。 我的意思是代替: 在此输入图像描述

我要这个: ![在此处输入图像说明

任何帮助将非常感谢!

谢谢...

您可以使用自定义components执行以下操作:

使用@ lisdey89打开菜单行为更新

const ValueContainer = ({ children, ...props }) => {
  const { getValue, hasValue } = props;
  const nbValues = getValue().length;
  if (!hasValue) {
    return (
      <components.ValueContainer {...props}>
        {children}
      </components.ValueContainer>
    );
  }
  return (
    <components.ValueContainer {...props}>
      {`${nbValues} items selected`}
    </components.ValueContainer>
  );
};
const options = [
  { label: "label 1", value: 1 },
  { label: "label 2", value: 2 },
  { label: "label 3", value: 3 },
  { label: "label 4", value: 4 }
];
function App() {
  const components = { ValueContainer };
  return <Select isMulti components={components} options={options} />;
}

这是一个实例

在我继续根据@Laura的答案进行搜索之后,我最终得到了这个解决方案,以显示所选项目的数量并保持ValueContainer的默认行为,也许其他人可能会发现它很有用:

const ValueContainer = ({ children, ...props }) => {
  const { getValue, hasValue } = props;
  const nbValues = getValue().length;
  if (!hasValue) {
    return (
      <components.ValueContainer {...props}>
        {children}
      </components.ValueContainer>
    );
  }
  return (
    <components.ValueContainer {...props}>
      {
        `${nbValues} items selected`
      }
    </components.ValueContainer>
  );
};

这是一个例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM