自定义组件“ValueContainer"的 React-Select 失去焦点 [英] React-Select losing focus for custom component "ValueContainer"

查看:25
本文介绍了自定义组件“ValueContainer"的 React-Select 失去焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We have a use case where we have to render multiple different versions of the value container for the multiselect dropdown depending on how many options are selected. The code snippet below shows one of the cases. Another version of this renders a <SingleValue /> instead of placeholder.

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

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

This seems to be working well, however we lose keyboard navigation upon selection of one of the options. Am I forgetting to pass certain props or a ref?

自定义 ValueContainers 的键盘导航示例如下:https://codesandbox.io/s/rjvkzk1nn?from-embed

An example of dropped keyboard navigation for custom ValueContainers can be found here: https://codesandbox.io/s/rjvkzk1nn?from-embed

推荐答案

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

Keyboard is not working anymore because you miss the Input component that is focused when you open the Menu.

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

ValueContainer has two objects when there's no value selected:

  • 占位符
  • 输入

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

when you select one (or multiple) value(s) then it changes for:

  • SingleValueMultiValue
  • 输入

在您之前的示例中,您删除了这两个.

with your previous example, you were removing those two.

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

To keep the keyboard features, you need to keep the Input component. The following code is a combination of your code and expectation and keeping the Input component:

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} />;
}

实例.

这篇关于自定义组件“ValueContainer"的 React-Select 失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆