A7D*_*7DC 10 javascript arrays reactjs react-select
我有一个简单的 React 组件,它获得一个初始状态:
this.state = {
currentObject: {
isYounger: false
}
}
Run Code Online (Sandbox Code Playgroud)
然后我react-select
用默认值渲染 a this.state.currentObject.isYounger
:
<Select
name={"age"}
value={this.state.currentObject.isYounger}
onChange={newValue => this.addIsYoungerValue(newValue)}
options={isYoungerOptions}
/>
Run Code Online (Sandbox Code Playgroud)
由于某种原因,该值未设置。为什么是这样?
版本:
"react-select": "^2.4.2",
小智 10
还有另一种方法可以使用value作为defaultValue。就我而言,我使用“id”和“industry”而不是“label”和“value”
this.state = {
interested_industries: [{id:"ANY", industry:"ANY"}]
}
Run Code Online (Sandbox Code Playgroud)
在选择组件中:-
<Select
name="interested_industries"
options={industries}
value={interested_industries}
getOptionLabel={ x => x.id}
getOptionValue={ x => x.industry}
onChange={this.handleSelect}
isMulti
/>
Run Code Online (Sandbox Code Playgroud)
小智 9
这里的问题不在于状态选择,实际问题是标签没有显示出来。
因此,根据您的addIsYoungerValue
功能,您将 的值设置this.state.currentObject.isYounger
为整个对象。即{ value: true, label: "Younger" }
。所以,这个问题可以通过改变初始状态的值来解决。
this.state = {
array: [],
currentObject: {
isYounger: { value: true, label: "Younger" }
}
};
Run Code Online (Sandbox Code Playgroud)
和 hurrey,将显示默认值标签..
您的defaultValue
或value
必须是对象。在你这样的情况下:
defaultValue={isYoungerOptions[0]}
Run Code Online (Sandbox Code Playgroud)
或者
this.state = {
array: [],
currentObject: {
isYounger: { value: "true", label: "Younger" }
}
};
Run Code Online (Sandbox Code Playgroud)
这里有一个活生生的例子。
归档时间: |
|
查看次数: |
18137 次 |
最近记录: |