首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在'react-native-dropdown-picker‘中设置默认值

在'react-native-dropdown-picker‘中设置默认值
EN

Stack Overflow用户
提问于 2020-12-24 16:53:36
回答 1查看 1K关注 0票数 0

我在我的项目中使用了react-native-dropdown-picker。我有一个类似这样的状态数组:[{value: "Bagerhat"},{value: "Bagerhat"}]。因此,在ComponentDidMount中,我将这个数组改为[{label: "Bagerhat"},{label: "Bagerhat"}],因为react-native-dropdown-picker需要在它的项目数组中使用标签。下面是我的DropDownPicker组件:

代码语言:javascript
复制
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由于某种原因抛出了标签错误。为什么会这样呢?

EN

回答 1

Stack Overflow用户

发布于 2020-12-24 17:04:34

它崩溃的原因是它不能接受null作为默认值,你应该删除默认值中的三元if else,并在构造函数中设置this.state.state,如下所示。

代码语言:javascript
复制
export default class Picker extends Component {
   constructor(){
     this.state={
        state:'',
     }
  }
} 

在return函数中,将其更改为

代码语言:javascript
复制
<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})}
    />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65436042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档