【问题标题】:Setting a default value with react-select not working使用 react-select 设置默认值不起作用
【发布时间】:2019-08-22 22:24:27
【问题描述】:

我有一个简单的 React 组件,它获取初始状态:

this.state = {
  currentObject: {
    isYounger: false
  }
}

然后我用默认值this.state.currentObject.isYounger渲染一个react-select

    <Select
      name={"age"}
      value={this.state.currentObject.isYounger}
      onChange={newValue => this.addIsYoungerValue(newValue)}
      options={isYoungerOptions}
    />

由于某种原因,未设置该值。这是为什么呢?

Codesandbox

版本:

"react-select": "^2.4.2",

【问题讨论】:

  • 你能指定你使用的 react-select 版本吗?
  • 谢谢@DharaVihol 我已经用版本更新了 OP
  • 您似乎遇到了问题,因为您尝试设置 Boolean 值。您可以使用 String 值尝试一次,以便我们了解根本原因,这将有助于解决问题。 @A7DC
  • 感谢@DharaVihol,我已更新为使用字符串值而不是布尔值,但这无济于事。我也用可编辑的沙箱更新了 OP
  • 你也可以提供defaultValue prop。如此处所述。 https://github.com/JedWatson/react-select

标签: javascript arrays reactjs react-select


【解决方案1】:

还有另一种方法可以使用 value 作为您的 defaultValue。在我的例子中,我使用了“id”和“industry”而不是“label”和“value”

this.state = {
     interested_industries: [{id:"ANY", industry:"ANY"}]
}

在选择组件中:-

<Select 
    name="interested_industries"
    options={industries}
    value={interested_industries}
    getOptionLabel={ x => x.id}
    getOptionValue={ x => x.industry}
    onChange={this.handleSelect}
    isMulti
/>

【讨论】:

    【解决方案2】:

    您的defaultValuevalue 必须是对象。在你的情况下是这样的:

    defaultValue={isYoungerOptions[0]}
    

    this.state = {
       array: [],
       currentObject: {
         isYounger: { value: "true", label: "Younger" }
       }
     };
    

    这里是live example

    【讨论】:

      【解决方案3】:

      这里的问题不在于状态选择,实际问题是标签没有显示。

      因此,根据您的 addIsYoungerValue 函数,您将 this.state.currentObject.isYounger 的值设置为整个对象。即{ value: true, label: "Younger" }。所以,这个问题可以通过如下改变初始状态的值来解决。

      this.state = {
            array: [],
            currentObject: {
              isYounger: { value: true, label: "Younger" }
            }
          };
      

      还有,会显示默认值标签..

      【讨论】:

        猜你喜欢
        • 2016-04-23
        • 1970-01-01
        • 2017-11-18
        • 1970-01-01
        • 2017-09-15
        • 2011-01-03
        • 2022-08-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多