我在我的项目中使用了react-native-dropdown-picker。我有一个类似这样的状态数组:[{value: "Bagerhat"},{value: "Bagerhat"}]。因此,在ComponentDidMount中,我将这个数组改为[{label: "Bagerhat"},{label: "Bagerhat"}],因为react-native-dropdown-picker需要在它的项目数组中使用标签。下面是我的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})}
/>
现在,this.state.state就像“Bagerhat”一样出现了。但是它显示label的错误是未定义的。它抛出这个错误的原因。在dropdown上,如果我删除了defaultvalue,它会显示状态,但defaultValue由于某种原因抛出了标签错误。为什么会这样呢?
发布于 2020-12-24 17:04:34
它崩溃的原因是它不能接受null作为默认值,你应该删除默认值中的三元if else,并在构造函数中设置this.state.state,如下所示。
export default class Picker extends Component {
constructor(){
this.state={
state:'',
}
}
} 在return函数中,将其更改为
<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})}
/>https://stackoverflow.com/questions/65436042
复制相似问题