如何将 defaultOption 添加到 AsyncSelect?

How to add defaultOption to AsyncSelect?

我正在为我的组件使用 Async react-select,但无法解决默认选项的问题。文档无法帮助我,因为没有与我的问题相关的示例。

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;

我想添加一个选项,让用户可以 select 所有选项。所以在 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 returns 添加自定义选项。

例如,您可以使用此方法将一个特殊选项附加到您的数组:

const appendSpecialOption = filteredOptions => {
  return [
    { label: "All Campaigns", value: "-2", group: true },
    ...filteredOptions
  ];
};

保持 defaultOptions 为 True(不是数组)。

这是您的场景的简化版本,但希望对您有所帮助: