javascript - 如何将 defaultOption 添加到 AsyncSelect?

标签 javascript reactjs react-select

我正在为我的组件使用 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.

当我们这样做时,我只会在我的下拉列表中得到默认选项,就像这样` enter image description here

但我的目标是得到像这张图片中那样的组件`

enter image description here

最佳答案

我认为实现所需结果的最佳方法是向任何 campaignToOption 返回的内容添加自定义选项。

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

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

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

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

Edit react-codesandboxer-example

关于javascript - 如何将 defaultOption 添加到 AsyncSelect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54535185/

相关文章:

css - 我们如何水平排列 react 选择标题和相应的组合框?

javascript - 在可排序列表 JQuery 之间添加可调整大小的元素

javascript - React/Enzyme 组件函数不更新状态

javascript - react 选择:在多选下拉列表中预先选择一个值

reactjs - 如何在 react 查询中重新获取集合的单个项目

javascript - jsreact - 获取 http ://localhost:8080/manifest. json 404(未找到)

javascript - React-select 不渲染数据

javascript - jQuery 下一个循环不会回到第一个 child

javascript - 传递值将 Ajax 抛出到一个 php 文件

javascript - 如何使用 fetch() 在 ReactJS 中发送 HTTP header