首页 > 解决方案 > 如何在 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 中创建嵌套组。

标签: javascriptreactjsreact-select

解决方案


对于任何来这里有类似需求的人,我实现了这个递归解决方法。

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


推荐阅读