首页 > 解决方案 > React-Select 失去自定义组件“ValueContainer”的焦点

问题描述

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

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

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

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

标签: reactjsreact-select

解决方案


键盘不再工作,因为您错过了Input打开Menu.

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

  • Placeholder
  • Input

当您选择一个(或多个)值时,它会更改为:

  • SingleValue或者MultiValue
  • 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} />;
}

活生生的例子


推荐阅读