首页 > 解决方案 > react-select 不会显示默认值

问题描述

我正在尝试根据一组值在 react-select 中显示默认值。我已确认该值等于我要比较的值。我浏览了这篇文章这篇文章这篇文章这篇文章这篇文章这篇文章。尽管有相似之处,但defaultValue仍然没有设定。我已经通过登录确认我的比较器的结果是相同的,都是大写的,都是字符串。

我的选择元素是

   <Select
    name="disposition"
    classNamePrefix="select"
    options={statusOptions}
    ref={selectInputRefPlan}
    styles={singleStylesRowComp}
    defaultValue={statusOptions.filter(
      ({ value }) => value.value === lead.disposition
    )}
  />

我的数组是

 const statusOptions = [
    { value: "HOT", label: i18n._(t`HOT`) },
    { value: "WIP", label: i18n._(t`WIP`) },
    { value: "LOST", label: i18n._(t`LOST`) },
    { value: "DNC", label: i18n._(t`DNC`) },
    { value: "WON", label: i18n._(t`WON`) },
    { value: "NEW", label: i18n._(t`NEW`) },
  ];

我正在测试value而不是label,因此不会出现翻译问题。当我记录响应时value.value === 'NEW'lead.disposition === 'NEW'但是,defaultValue不会设置。我也尝试过 prop value,并阅读了 6 或 7 个类似的帖子。有简单的语法错误吗?还是我缺少的其他东西?

这是一个演示该问题的沙盒链接

标签: reactjsreact-select

解决方案


错误在您的过滤器功能中。您分解 value,然后访问 value.value。这是未定义的。

相反,采用不分解的选项参数,并访问 option.value。

<Select
  name="disposition"
  classNamePrefix="select"
  options={statusOptions}
  ref={selectInputRefPlan}
  styles={singleStylesRowComp}
  defaultValue={statusOptions.filter((option) => option.value === lead.disposition)}
/>;

推荐阅读