React Native 选取器仅显示最后一个数组项

yxyvkwin  于 2022-12-19  发布在  React
关注(0)|答案(1)|浏览(181)

我已经用我的脑袋撞墙好几个小时了,试图让它正常工作。我试图使用“@react-native-community/picker”模块在React Native中显示一个“picker”下拉列表。下面是代码:

import React, { Component } from "react";
import { Button, Dimensions, Image, ImageBackground, Platform, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";

import {Picker} from '@react-native-community/picker';

const deviceWidth = Dimensions.get("window").width;

export default class Results extends Component {
constructor(props) {
  super(props);

  this.state = {
    venues: [{"name": "Carmine's", "id": 0, "name": "Carmines", "id": 1, "name": "Joe's", "id": 2, "name": "Johnny V's", "id": 3, "name": "Cheescake Factory", "id": 4}],
    selectedItem:''
  };
}

  render() {
   return (

      <View style={styles.main}>

       <Picker
       selectedValue={this.state.selectedItem}
       style={{width: deviceWidth, height: 40 }}
       onValueChange={(itemValue, itemIndex) => this.setState({selectedItem: itemValue})}>

       { this.state.venues.map( (v, key)=>{
       return <Picker.Item label={v.name} value={v.id} key={key} />
       }) }

       </Picker>

      </View>

   );  //return
  }  //render

问题是“picker”控件显示,但是只显示数组中的“最后一个”项目(“Cheescake Factory”)。据我所知,“this.state.venues.map”应该循环通过数组,并将所有值填充到“picker”下拉选择框中...
如前所述,这是要把我逼疯了...任何建议都非常感谢!我提前感谢你。

t9aqgxwy

t9aqgxwy1#

你已经很接近了,但是看起来你正在尝试遍历一个只有一个对象的数组。试着为每个name和id属性创建一个单独的对象,然后像你这样遍历。这将给予你一个对象数组。所以从技术上讲,你只有一个值的数组(一个对象),所以它的长度为1,这就是为什么你只返回一个值。一旦你把这些值分成一个对象数组,你的长度将为5。祝你好运!

this.state = {
    venues: [{"name": "Carmine's", "id": 0}, {"name": "Carmines", "id": 1}, {"name": "Joe's", "id": 2}, {"name": "Johnny V's", "id": 3}, {"name": "Cheescake Factory", "id": 4}],
    selectedItem:''
  };

相关问题