react-select 不使用 defaultValue 更改标签
react-select does not change label with defaultValue
为什么react-select不改变标签,而是改变值?
const options = [
{ label: 'One', value: 'One' },
{ label: 'Two', value: 'Two' },
];
<Select
defaultValue={{label: "One", value: "One"}}
options=options
/>
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
/>
React Select 默认值采用一个对象来设置默认值。你代码中的问题很简单,
1- 您需要通过将选项包装在 {} 中来绑定选项,例如 {options}
然后设置默认值:
2- defaultValue={options[1]}
或 defaultValue={{ label: 'Two', value: 'Two' }}
检查沙盒上的示例:
sample example
需要明确的是,标签只会更改 select 中显示的文本,但实际值受对象 value
键的限制
为什么react-select不改变标签,而是改变值?
const options = [
{ label: 'One', value: 'One' },
{ label: 'Two', value: 'Two' },
];
<Select
defaultValue={{label: "One", value: "One"}}
options=options
/>
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
/>
React Select 默认值采用一个对象来设置默认值。你代码中的问题很简单,
1- 您需要通过将选项包装在 {} 中来绑定选项,例如 {options}
然后设置默认值:
2- defaultValue={options[1]}
或 defaultValue={{ label: 'Two', value: 'Two' }}
检查沙盒上的示例: sample example
需要明确的是,标签只会更改 select 中显示的文本,但实际值受对象 value
键的限制