我正在为我的组件使用 Async react-select,但无法解决默认 Options 的问题。文档无法帮助我,因为没有与我的问题相关的示例。
const campaignToOption = campaign => ({value: campaign.id, label: campaign.name});
const loadOptionsWrapper = fetchAll =>
input => fetchAll({
_limit: 10000,
q: input,
_sort: 'name',
_order: 'asc',
}).then(campaigns => _(campaigns).reject('meta').map(campaignToOption).values());
const defaultProps = {
options: [],
placeholder: 'Campaign: Not selected',
};
const CampaignFilter = props => {
return <Async
defaultOptions={[{label: 'All Campaigns', value: '-2', group: true}]}
loadOptions={loadOptionsWrapper(props?.actions?.fetchAllCampaigns)}
{...defaultProps}
{...props}
/>;
};
export default CampaignFilter;
我想添加一个选项,让用户选择所有选项。所以在 AsyncSelect 的情况下,选项被异步加载。文档说我们可以使用 defaultOptions。
The defaultOptions prop determines "when" your remote request is initially fired. There are two valid values for this property. Providing an option array to this prop will populate the initial set of options used when opening the select, at which point the remote load only occurs when filtering the options (typing in the control). Providing the prop by itself (or with 'true') tells the control to immediately fire the remote request, described by your loadOptions, to get those initial values for the Select.
当我们这样做时,我只会在我的下拉列表中得到默认选项,就像这样`
但我的目标是得到像这张图片中那样的组件`
最佳答案
我认为实现所需结果的最佳方法是向任何 campaignToOption
返回的内容添加自定义选项。
例如,您可以使用此方法将一个特殊选项附加到您的数组:
const appendSpecialOption = filteredOptions => {
return [
{ label: "All Campaigns", value: "-2", group: true },
...filteredOptions
];
};
保持 defaultOptions
为 True(不是数组)。
这是您的场景的简化版本,但希望对您有所帮助:
关于javascript - 如何将 defaultOption 添加到 AsyncSelect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54535185/