我正在使用 react-select 库在我的项目中实现搜索和选择功能。
作为基本用法,我只能选择搜索后返回的选项。看起来像其代码是:
<AsyncSelect
onChange={(item) => _selectedItemChange(item)}
loadOptions={loadItemOptions}
placeholder='Start typing'
/>
现在,我想要在选择框的下端有一个按钮,这样我就可以像“找不到?”添加新类型的东西。像这样的东西。我也希望那个按钮的 onClick 功能是我自己的。
我该怎么做?
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 }} />
从@PasVV 的回答来看,我能做点什么,我一直想做。 通过将道具传递给 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 React from "react";
import { option_data } from "./data";
import { components } from "react-select";
import AsyncCreatableSelect from "react-select/async-creatable";
const Option = (props) => {
return (
<>
<components.Option {...props}>
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "space-between"
}}
>
<div>{props.children}</div>
<div>
<button
onClick={(e) => {
e.stopPropagation();
console.log("Delete clicked: ", props.data.id);
}}
>
Edit
</button>
<button
onClick={(e) => {
e.stopPropagation();
console.log("Delete clicked: ", props.data.id);
}}
>
Delete
</button>
</div>
</div>
</components.Option>
</>
);
};
const App = () => {
const filterInput = (inputValue) => {
return option_data.filter((i) =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
};
const promiseOptions = (inputValue) =>
new Promise((resolve) => {
setTimeout(() => {
resolve(filterInput(inputValue));
}, 1000);
});
return (
<div className="App">
<AsyncCreatableSelect
components={{ Option }}
loadOptions={promiseOptions}
/>
</div>
);
};
export default App;