首页 > 解决方案 > react-select 在 MenuList 中添加搜索输入

问题描述

我正在使用 react-select (https://react-select.com),我试图在 MenuList 本身(顶部)内添加搜索输入,而不是从容器中搜索的默认行为。

<Select
   ...
   components={{
      ...
      MenuList: (props: any) => {
         return (
            <components.MenuList {...props}>
               <div className="search-wrapper">
                  <input 
                     value={search}
                     onChange={searchChange}
                     placeholder="Search"/>
                </div>
                {props.children}
             </components.MenuList>
          );
       },
   }}
>
</Select>

它正在工作,我在菜单顶部得到了一个很好的输入:

在此处输入图像描述

但输入似乎被禁用。(在输入中添加 disabled=false 不会产生任何影响)

有什么想法吗?为什么会这样?实现此类功能的正确方法是什么?

标签: reactjsreact-select

解决方案


这个变体对我有用。

首先你应该innerPropscomponents.Menu. 我没有尝试过components.MenuList,但我想它也应该可以。

<components.MenuList {...props} innerProps={undefined}>

然后您将能够使用输入,但菜单会在每次单击时关闭,因此: 其次,您应该使用menuIsOpenprop 控制菜单状态。首先你可以覆盖 SelectContainer:

const SelectContainer: React.FC<CommonProps<object, false>> = ({ children, ...props }) => (
  <components.SelectContainer {...props}>
    <div onClick={() => setMenuOpen(true)}>
      {children}
    </div>
  </components.SelectContainer>
);

然后添加一个处理程序以在单击内部菜单时关闭菜单。


推荐阅读