【问题标题】:react-select does not change label with defaultValuereact-select 不使用 defaultValue 更改标签
【发布时间】:2020-01-30 17:23:54
【问题描述】:

为什么 react-select 不改变标签,而是改变值?

const options = [
  { label: 'One', value: 'One' },
  { label: 'Two', value: 'Two' },
];

<Select
  defaultValue={{label: "One", value: "One"}}
  options=options
/>

【问题讨论】:

  • 其实我把这个 Select 包装到 redux-form 组件
  • 我在对象格式的 redux-form 中为 initialValues 添加了默认值,它可以工作。帮助大家initialValues: { type: {label: "One", value: "One"} }

标签: reactjs react-select


【解决方案1】:

React Select 默认值需要一个对象来设置默认值。你代码中的问题很简单,

1- 您需要通过将选项包装在 {} 中来绑定选项,例如 {options}

然后设置defaultValue:

2- defaultValue={options[1]}defaultValue={{ label: 'Two', value: 'Two' }}

查看沙盒上的示例: sample example

只是为了清楚标签只会改变选择中显示的文本,但实际值由对象中的value键限制

【讨论】:

  • 它只适用于纯 Select,但不适用于 redux-form 包装
【解决方案2】:

defaultValue 属性只会接受一个值。对于您的示例,如果将 defaultValue 设置为“One”,它将自动将标签设置为上面的相应选项。一个例子是:

const options = [
  { label: 'One', value: 'One' },
  { label: 'Two', value: 'Two' },
];

//the defaultValue will look inside the options array and use the label where the value is the same
<Select
  defaultValue="One"
  options=options
/>

在此处查看更多信息https://www.npmjs.com/package/react-select

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2021-07-11
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多