javascript - 如何在 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>
);
};
然后在您选择的组件中,将组件替换为我们刚刚创建Option
的自定义组件。Option
编辑
有一个开放的拉取请求来支持此功能: https ://github.com/JedWatson/react-select/pull/2750
推荐阅读
- python - 从数据字典创建实例时出现 Pyomo KeyError
- python - 如何在python中循环?
- if-statement - awk if-else 和变量重新分配
- aws-lambda - 将端点作为 AWS Lambda 的优势
- c# - 检查asp.net中的第二个参数
- android - Retrofit 抱怨这个 json 不是一个数组
- php - 为数组中的每个条目循环运行mysql查询
- php - 如何安全地检查超全局 POST['key'] 的类型?
- r - 使用 library(xml2) [in R] 解析 XML 数据
- c# - 刷新后 SelectedNode 不工作总是显示 null