简体   繁体   中英

Set default value in 'react-native-dropdown-picker'

I'm using react-native-dropdown-picker in my project. I have an array of states which is like this: [{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. Here's my DropDownPicker component:

 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. But it's showing error for label is undefined. 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. 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,

export default class Picker extends Component {
   constructor(){
     this.state={
        state:'',
     }
  }
} 

And in return function, change that to

<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})}
    />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM