React-Select失去自定义组件“ ValueContainer”的焦点]

问题描述 投票:1回答:1

我们有一个用例,根据选择的选项数量,我们必须为多选下拉列表呈现值容器的多个不同版本。下面的代码段显示了其中一种情况。此版本的另一个版本呈现<SingleValue />而不是占位符。

<ValueContainer {...props}>
    <Placeholder {...props}>
    {!props.selectProps.inputValue && `${length} selected`}
    </Placeholder>
    {children[1]}
</ValueContainer>

这似乎运行良好,但是选择其中一个选项后,我们将失去键盘导航功能。我是否忘记传递某些道具或裁判?

自定义ValueContainer的键盘导航示例已删除,可在此处找到:https://codesandbox.io/s/rjvkzk1nn?from-embed

reactjs react-select
1个回答
0
投票

键盘不再起作用,因为您错过了打开Input时聚焦的Menu组件。

ValueContainer当没有选择任何值时有两个对象:

  • Placeholder
  • Input

[当您选择一个(或多个)值时,其值将更改为:

  • [SingleValueMultiValue
  • Input

与以前的一样,您要删除这两个。

要保留键盘功能,您需要保留Input组件。以下代码是您的代码和期望的结合,并保留Input组件:

const ValueContainer = ({ children, ...props }) => {
  const { getValue, hasValue } = props;
  const newChildren = _.cloneDeep(children);
  const nbValues = getValue().length;
  newChildren[0] = `${nbValues} items selected`;

  if (!hasValue) {
    return (
      <components.ValueContainer {...props}>
        {children}
      </components.ValueContainer>
    );
  }
  return (
    <components.ValueContainer {...props}>
      {newChildren}
    </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

© www.soinside.com 2019 - 2024. All rights reserved.