如何在 React Select (V2) 中创建嵌套选项组?

IT技术 javascript reactjs react-select
2021-05-01 22:14:37

在 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 中创建嵌套组。

1个回答

对于任何有类似需求的人,我实施了这种递归解决方法。

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