如何使用 react-select v2 呈现数量 selected 项目
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} />;
}
这里是live example.
在我根据@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>
);
};
这里是example
我正在使用 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} />;
}
这里是live example.
在我根据@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>
);
};
这里是example