如何实用地打开 React select 菜单

How to open react select menu pragmatically

我想在单击按钮时打开 React select 菜单。


这里是代码沙盒link

https://codesandbox.io/s/material-demo-kssrb

我知道一个反应 select 属性 'menuIsOpen',这个道具的缺点是菜单总是打开的,默认关闭行为因此丢失。

感谢任何帮助。

一旦用户 select 从 select 框中输入任何内容,您就可以将 "menuIsOpen" 的值设置为 false

看到这个。我已经做了必要的修改

https://codesandbox.io/s/material-demo-guo4i

连同 menuIsOpen 道具,您还需要 onBlur 事件来让它变黑。

因为 menuIsOpen 道具确实重置了 Select 组件的所有 on-* 事件。

此外,要使 onBlur 起作用,您需要使用 setFocus 将焦点设置到下拉元素。

你可以在这里查看。 https://codesandbox.io/s/material-demo-gxvxr

您可以尝试使用存储组件的引用,在其上调用 .focus()。 并传递给 React Select prop openMenuOnFocus.

codesandbox 示例:https://codesandbox.io/s/react-select-hooks-forked-qol5m

短精华:

  const selectRef = useRef();
  const onClick = () => {
    selectRef.current.focus();
  };

    <Dropdown
      openMenuOnFocus={true}
      ref={selectRef}
    />