[英]Set default value in 'react-native-dropdown-picker'
I'm using react-native-dropdown-picker
in my project.我在我的项目中使用react-native-dropdown-picker
。 I have an array of states which is like this: [{value: "Bagerhat"},{value: "Bagerhat"}]
.我有一个状态数组,如下所示: [{value: "Bagerhat"},{value: "Bagerhat"}]
。 So, in ComponentDidMount i'm changing this array by [{label: "Bagerhat"},{label: "Bagerhat"}]
because react-native-dropdown-picker needs label in it's item's array.因此,在 ComponentDidMount 中,我通过[{label: "Bagerhat"},{label: "Bagerhat"}]
更改此数组,因为 react-native-dropdown-picker 需要 label 在它的项目数组中。 Here's my DropDownPicker
component:这是我的DropDownPicker
组件:
componentDidMount() { var sts = [{value: "Bagerhat"},{value: "Bagerhat"}] sts = sts.map(item => { return { label: item.value }; }); this.setState({ states: sts }) } <DropDownPicker items={this.state.states} defaultValue={(this.state.state?== ''. this.state:state: null )} containerStyle={{ height, 50:width, width - 40:alignSelf:'center' }} style={{backgroundColor: '#fff'}} itemStyle={{justifyContent: 'flex-start'}} dropDownStyle={{ marginTop, 2: backgroundColor. '#fff' }} onChangeItem={item => this:setState({state.item.label})} />
Now this.state.state
is present like 'Bagerhat' for example.现在this.state.state
像“Bagerhat”一样出现。 But it's showing error for label
is undefined.但它显示label
的错误未定义。 Why it's throwing this error.为什么会抛出这个错误。 On dropdown it's showing states if i remove defaultvalue but defaultValue is throwing label error for some reason.如果我删除默认值但默认值由于某种原因抛出 label 错误,它会在下拉列表中显示状态。 Why is that?这是为什么?
The reason it is crashing is it can't take null as a default value, You should remove ternary if else in default value and set this.state.state in constructor as an example below,它崩溃的原因是它不能将 null 作为默认值,您应该在默认值中删除三元 if else 并设置 this.state.state 作为下面的构造函数示例,
export default class Picker extends Component {
constructor(){
this.state={
state:'',
}
}
}
And in return function, change that to作为回报 function,将其更改为
<DropDownPicker
items={this.state.states}
defaultValue={(this.state.state)}
containerStyle={{ height: 50,width: width - 40,alignSelf:'center' }}
style={{backgroundColor: '#fff'}}
itemStyle={{justifyContent: 'flex-start'}}
dropDownStyle={{ marginTop: 2, backgroundColor: '#fff' }}
onChangeItem={item => this.setState({state:item.label})}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.