【问题标题】:Set default value in 'react-native-dropdown-picker'在“react-native-dropdown-picker”中设置默认值
【发布时间】:2020-12-24 17:22:31
【问题描述】:

我在我的项目中使用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 的错误未定义。为什么会抛出这个错误。如果我删除默认值但默认值由于某种原因抛出标签错误,它会在下拉列表中显示状态。这是为什么呢?

【问题讨论】:

  • 你的情况是什么this.state.state
  • 它只是像“Bagerhat”这样的字符串@LeriGogsadze
  • 我认为应该是键值对。 { label: "Bagerhat" }
  • 也试过了。没用。

标签: javascript react-native


【解决方案1】:

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

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

在返回函数中,将其更改为

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

【讨论】:

  • 不幸的是,事实并非如此。它给出了同样的错误。
猜你喜欢
  • 1970-01-01
  • 2020-06-23
  • 2017-09-11
  • 2022-06-27
  • 2022-12-24
  • 2020-12-20
  • 2021-11-19
  • 2023-01-05
  • 2021-12-05
相关资源
最近更新 更多