![](/img/trans.png)
[英]How do I create new option if there are no left while searching in React-Select v2?
[英]How can I create nested option groups in React Select (V2)?
在 React-Select V2 中,我们可以通过传递一个options
参数来创建选项组,如下所示:
options = [
{ label: 'Group', options: [
{ label: 'Option 1', value: '1' },
{ label: 'Option 2', value: '2' }
]}
]
我需要能够深入另一层,例如:
options = [
{ label: 'Group', options: [
{ label: 'Option 1', value: '1' },
{ label: 'Option 2', options: [
{ label: 'Option 2-a', value: '2a' },
{ label: 'Option 2-b', value: '2b' },
]}
]}
]
这将在“选项 2”下的组中显示选项“选项 2-a”和“选项 2-b”。 上面的方法不是开箱即用的,所以我想知道是否有办法在 React-Select V2 中创建嵌套组。
对于任何有类似需求的人,我实施了这种递归解决方法。
const renderNestedOption = (props, label, nestedOptions) => {
const {
cx,
getStyles,
innerProps,
selectOption,
} = props;
// Will be applied to nested optgroup headers
const nestedLabelClassName = cx(
css(getStyles('groupHeading', props)),
{ option: true },
'nested-optgroup-label',
);
return (
<div className="nested-optgroup">
<div className={nestedLabelClassName}>
{label}
</div>
{nestedOptions.map((nestedOption) => {
if (nestedOption.options) {
// Read below
// Read above
return renderNestedOption(props, nestedOption.label, nestedOption.options);
}
const nestedInnerProps = innerProps;
nestedInnerProps.onClick = () => selectOption(nestedOption);
return (
<div className="nested-optgroup-option" key={nestedOption.value}>
<components.Option {...props} innerProps={nestedInnerProps}>
{nestedOption.label}
</components.Option>
</div>
);
})}
</div>
);
};
const Option = (props) => {
const {
children,
data,
} = props;
const nestedOptions = data.options;
if (nestedOptions) {
const label = data.label;
return renderNestedOption(props, label, nestedOptions);
}
return (
<components.Option {...props}>
{children}
</components.Option>
);
};
然后在您的 select 组件中,将Option
组件替换为我们刚刚创建的自定义Option
组件。
有一个开放的拉取请求来支持这个功能: https : //github.com/JedWatson/react-select/pull/2750
在React-Select V2中,我们可以通过传递options
参数来创建选项组,如下所示:
options = [
{ label: 'Group', options: [
{ label: 'Option 1', value: '1' },
{ label: 'Option 2', value: '2' }
]}
]
我需要能够更深入一些,例如:
options = [
{ label: 'Group', options: [
{ label: 'Option 1', value: '1' },
{ label: 'Option 2', options: [
{ label: 'Option 2-a', value: '2a' },
{ label: 'Option 2-b', value: '2b' },
]}
]}
]
它将在“选项2”下的组中显示选项“选项2-a”和“选项2-b”。 上面的方法不是开箱即用的,所以我想知道是否有一种方法可以在React-Select V2中创建嵌套组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.