在 react-select 中的选项末尾附加一个按钮
Append a button at the end of options in react-select
我正在使用 react-select 库在我的项目中实现搜索和 select 功能。
作为基本用法,我只能select搜索后返回的选项。看起来像 this 其代码是:
<AsyncSelect
onChange={(item) => _selectedItemChange(item)}
loadOptions={loadItemOptions}
placeholder='Start typing'
/>
现在,我想要在 select 框的下端有一个按钮,这样我就可以执行 'Not found? Add New' 类型的操作。类似于 this。我还希望那个按钮的 onClick 功能是我自己的。
我该怎么做?
为了实现你的目标,你可以replace react-select MenuList
组件的逻辑。
您可以在 documentation 中找到一些示例。
我想这是在你的 react-select 组件中添加一些自定义功能的最佳方式。
从@PasVV 的回答来看,我能做点什么,我一直想做。
通过将 props 传递给 AsyncSelect 组件,我们可以制作自己的自定义菜单(react-select 中的可自定义组件),如下所示。
const CustomMenu = ({ innerRef, innerProps, isDisabled, children }) =>
!isDisabled ? (
<div ref={innerRef} {...innerProps} className="customReactSelectMenu">
{children}
<button
className="btn btn-info btn-sm btn-block"
onClick={() => ...}
>Add New</button>
</div>
) : null;
并将其传递给 <AsyncSelect/>
<AsyncSelect
onChange={_change}
loadOptions={loadVendorOptions}
placeholder='Start typing'
components={{ Menu: CustomMenu }}
/>
import { components } from 'react-select';
const SelectMenuButton = (props) => {
return (
<components.MenuList {...props}>
{props.children}
<button>Add new element</button>
</components.MenuList >
) }
<Select components={{ MenuList: SelectMenuButton }} />
我正在使用 react-select 库在我的项目中实现搜索和 select 功能。
作为基本用法,我只能select搜索后返回的选项。看起来像 this 其代码是:
<AsyncSelect
onChange={(item) => _selectedItemChange(item)}
loadOptions={loadItemOptions}
placeholder='Start typing'
/>
现在,我想要在 select 框的下端有一个按钮,这样我就可以执行 'Not found? Add New' 类型的操作。类似于 this。我还希望那个按钮的 onClick 功能是我自己的。
我该怎么做?
为了实现你的目标,你可以replace react-select MenuList
组件的逻辑。
您可以在 documentation 中找到一些示例。
我想这是在你的 react-select 组件中添加一些自定义功能的最佳方式。
从@PasVV 的回答来看,我能做点什么,我一直想做。 通过将 props 传递给 AsyncSelect 组件,我们可以制作自己的自定义菜单(react-select 中的可自定义组件),如下所示。
const CustomMenu = ({ innerRef, innerProps, isDisabled, children }) =>
!isDisabled ? (
<div ref={innerRef} {...innerProps} className="customReactSelectMenu">
{children}
<button
className="btn btn-info btn-sm btn-block"
onClick={() => ...}
>Add New</button>
</div>
) : null;
并将其传递给 <AsyncSelect/>
<AsyncSelect
onChange={_change}
loadOptions={loadVendorOptions}
placeholder='Start typing'
components={{ Menu: CustomMenu }}
/>
import { components } from 'react-select';
const SelectMenuButton = (props) => {
return (
<components.MenuList {...props}>
{props.children}
<button>Add new element</button>
</components.MenuList >
) }
<Select components={{ MenuList: SelectMenuButton }} />