使用 react-select 设置默认值不起作用
Setting a default value with react-select not working
我有一个获得初始状态的简单 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}
/>
由于某种原因,该值未设置。这是为什么?
版本:
"react-select": "^2.4.2",
此处的问题与状态选择无关,实际问题是标签未显示。
因此,根据您的 addIsYoungerValue
函数,您将 this.state.currentObject.isYounger
的值设置为整个对象。即 { value: true, label: "Younger" }
。所以,这个问题可以通过下面改变初始状态的值来解决。
this.state = {
array: [],
currentObject: {
isYounger: { value: true, label: "Younger" }
}
};
快点,将显示默认值标签..
您的 defaultValue
或 value
必须是对象。在你的情况下:
defaultValue={isYoungerOptions[0]}
或
this.state = {
array: [],
currentObject: {
isYounger: { value: "true", label: "Younger" }
}
};
这里是live example.
还有另一种方法可以使用 value 作为 defaultValue。在我的例子中,我使用了 "id" 和 "industry" 而不是 "label" 和 "value"
this.state = {
interested_industries: [{id:"ANY", industry:"ANY"}]
}
并且在 Select 组件中:-
<Select
name="interested_industries"
options={industries}
value={interested_industries}
getOptionLabel={ x => x.id}
getOptionValue={ x => x.industry}
onChange={this.handleSelect}
isMulti
/>
我有一个获得初始状态的简单 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}
/>
由于某种原因,该值未设置。这是为什么?
版本:
"react-select": "^2.4.2",
此处的问题与状态选择无关,实际问题是标签未显示。
因此,根据您的 addIsYoungerValue
函数,您将 this.state.currentObject.isYounger
的值设置为整个对象。即 { value: true, label: "Younger" }
。所以,这个问题可以通过下面改变初始状态的值来解决。
this.state = {
array: [],
currentObject: {
isYounger: { value: true, label: "Younger" }
}
};
快点,将显示默认值标签..
您的 defaultValue
或 value
必须是对象。在你的情况下:
defaultValue={isYoungerOptions[0]}
或
this.state = {
array: [],
currentObject: {
isYounger: { value: "true", label: "Younger" }
}
};
这里是live example.
还有另一种方法可以使用 value 作为 defaultValue。在我的例子中,我使用了 "id" 和 "industry" 而不是 "label" 和 "value"
this.state = {
interested_industries: [{id:"ANY", industry:"ANY"}]
}
并且在 Select 组件中:-
<Select
name="interested_industries"
options={industries}
value={interested_industries}
getOptionLabel={ x => x.id}
getOptionValue={ x => x.industry}
onChange={this.handleSelect}
isMulti
/>