React Native-从道具为React Native Picker创建动态数组

时间:2019-04-08 17:02:39

标签: reactjs react-native

我需要动态创建一个数组,该数组提供给react本机选择器以填充一周开始日期的列表,以用于填充轮换视图。

https://www.npmjs.com/package/react-native-picker-select

数据必须按照其文档中的说明作为数组提供:

The items for the component to render
- Each item should be in the following format:
{label: 'Orange', value: 'orange', key: 'orange', color: 'orange'}
- The label and the value are required
- The key and color are optional
- The key will be set to the label if not included
- The value can be any data type
- Must have at least one item

我创建了一个函数,该函数使用一个数据道具,其中包含一个星期开始日期文本和值的列表。 如下:

dateList = () => {
        return( this.props.user.weekCommencingDates.map( (x,i) => {

             let dataList= 'label:' + x.Text + ', value:' + x.Value; 

              return(
              dataList; 
              )
        } ));
    }

上面没有提供正确格式的数组,我得到一个空的选择器。有人可以给我任何建议吗?

下面列出了完整的类供参考:

    import React from 'react';
import { connect } from "react-redux";
import {StyleSheet, Button, View, Text, StatusBar, ScrollView, Picker, FlatList} from 'react-native';
const GlobalStyles = require('../assets/globalStyle');
import { Chevron } from 'react-native-shapes';
import TitleHeader from './util/TitleHeader';
import FixedHeader from './util/FixedHeader';
import CopyrightSpiel from './util/CopyrightSpiel';

import { withNavigation } from 'react-navigation';
import _ from 'lodash';
import moment from 'moment';
import RNPickerSelect from 'react-native-picker-select';

//TODO
//Show current week as initial week

class Rota extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      wcDateSelected: undefined,
      rotaList: [],
      favNumber: undefined,
      numbers: [
        {
          label: '1',
          value: 1,
        },
        {
          label: '2',
          value: 2,
        },
      ],
    };
  }

  componentDidMount() {
    let thisWeek = this.props.user.weekCommencingDates[0];

    this.getData(thisWeek.Value);
  }

  getData(value){
    const rotaList = this.props.user.rotaRecords;
    var filteredRotas = rotaList.filter(rota => rota.WeekCommencingDate === value);

    this.setState({wcDateSelected: value});
    this.setState({rotaList: filteredRotas});
  }

  dateList = () => {

    let dataList = this.props.user.weekCommencingDates.map(x => ({
      label: x.Text,
      value: x.Value
    }));
    return dataList;
  }

  _renderItem = data => {
    const item = data.item;

      let weekDay= ['Sun','Mon', 'Tues', 'Wed', 'Thurs', 'Fri',  'Sat'];
      const rotaDay = new Date(item.StartRotaDate).getDay();
      const startTime = item.StartTime.substring(0, item.StartTime.length - 3);
      const endTime = item.EndTime.substring(0, item.EndTime.length - 3);

      return (
          <View style={RotaStyles.tableRow}>
              <View style={[RotaStyles.tableCell, RotaStyles.tableCellOne,]}><Text style={RotaStyles.tableRowText}>{weekDay[rotaDay]}</Text></View>
              <View style={[RotaStyles.tableCell, RotaStyles.tableCellTwo,]}><Text style={RotaStyles.tableRowText}>{item.Venue}</Text></View>
              <View style={[RotaStyles.tableCell, RotaStyles.tableCellThree,]}><Text style={RotaStyles.tableRowText}>{startTime}</Text></View>
              <View style={[RotaStyles.tableCell, RotaStyles.tableCellFour,]}><Text style={RotaStyles.tableRowText}>{endTime}</Text></View>
          </View>
        );
  }

  _listEmptyComponent = () => {
    return (
        <View>
            <Text style={RotaStyles.noRotTxt} >* No rotas available for selected week</Text>
        </View>
    )
  }

  _listHeaderComponent = () => {
    return (
      <View style={RotaStyles.tableRow}>
        <View style={[RotaStyles.tableCell, RotaStyles.tableCellOne, RotaStyles.tableCellHeader  ]} ><Text style={RotaStyles.tableRowHeaderText}>Day</Text></View>
        <View style={[RotaStyles.tableCell, RotaStyles.tableCellTwo, RotaStyles.tableCellHeader  ]} ><Text style={RotaStyles.tableRowHeaderText}>Venue</Text></View>
        <View style={[RotaStyles.tableCell, RotaStyles.tableCellThree, RotaStyles.tableCellHeader  ]} ><Text style={RotaStyles.tableRowHeaderText}>Start</Text></View>
        <View style={[RotaStyles.tableCell, RotaStyles.tableCellFour, RotaStyles.tableCellHeader  ]} ><Text style={RotaStyles.tableRowHeaderText}>End</Text></View>
      </View>
    )
  }

  render() {

    return (
      <View style={RotaStyles.rotaContainer} >
        <StatusBar barStyle="light-content" />

        <View style={RotaStyles.rotaHeader}>
          <FixedHeader backButton={true}  />
        </View>

        <View style={RotaStyles.rotaBody}>
          <ScrollView>
          <TitleHeader sectionLocaleTxt='Shifts' sectionTxt='My Rota' sectionDesc='Your shifts for the selected month' sectionHyphen={true}  />
            <Text style={RotaStyles.pickerTitle} >Scroll to select W/C Date:</Text>
            <View style={RotaStyles.pickerWrap} >

              <Text>{this.dateList()}</Text>

            </View>
            <View style={[RotaStyles.pickerWrap, {marginTop:30}]} >

              <RNPickerSelect
                placeholder={{
                  label: 'Select a number or add another...',
                  value: null,
                  color: 'red',
                }}
                items={this.dateList()}
                onValueChange={value => {
                  this.setState({
                    favNumber: value,
                  });
                }}
                style={RotaStyles.dropDown}
              />
            </View>

            <View style={RotaStyles.rotaTable}>

              <FlatList
                scrollEnabled={true}
                data={this.state.rotaList}
                keyExtractor={(item, index) => index.toString()}
                ListEmptyComponent={this._listEmptyComponent}
                ListHeaderComponent={this._listHeaderComponent}
                renderItem={this._renderItem}
              />
            </View>
          </ScrollView>
        </View>

      </View>

    );
  }
}

const RotaStyles = StyleSheet.create({
  rotaContainer: {
    flex:1,
    alignItems:'center',
    textAlign:'center',
    backgroundColor:'#fff',
    alignSelf:'stretch',
  },
  rotaHeader:{
    height:120,
    alignSelf:'stretch',
  },
  pickerTitle:{

    fontSize:17,
    color:'#1C2344',
    fontWeight:'600',
    marginBottom:10,
    marginTop:15,
    marginLeft:15
  },
  rotaBody:{
    backgroundColor:'#fff',
    flex:3,
    alignSelf:'stretch',
  },
  dropDown:{
    backgroundColor:'#0e131e',
    padding:20,
    paddingLeft:15,
    paddingRight:15,
    fontSize:25,
  },
  rotaTable:{
    margin:8,
    marginTop:8,
    flex:1,
  },
  tableRow:{

    flexDirection:'row'
  },
  tableCell:{
    backgroundColor:'#f3f4f3',
    margin:4,
    padding:4,

  },
  tableRowText:{
    alignSelf:'center',

  },
  tableRowHeaderText:{
    alignSelf:'center',
    fontWeight:'700',
    textTransform:'uppercase',
    color:'#1C2344',
    marginTop:15

  },

  tableCellOne:{
    flex:1,
    textAlign:'left',
    alignSelf:'stretch',
  },
  tableCellTwo:{
    flex:3
  },
  tableCellThree:{
    flex:2
  },
  tableCellFour:{
    flex:1
  },
  tableCellHeader:{
    backgroundColor:'rgba(255,255,255,0.8)',

  },
  homeFooter:{
    marginBottom:15
  },
  pickerWrap:{
    backgroundColor:'#F4F4F4',
    marginLeft:15,
    marginRight:15,
  },
  picker:{
    color:'#fff'
  },
  noRotTxt:{
    fontWeight:'700',
    justifyContent: 'center',
    marginLeft:15,
    color:'#f79431',
    backgroundColor:'#F4F4F4',
    paddingVertical:8,
    paddingHorizontal:10,
    flex:1,
    textTransform:'uppercase',
marginRight:15

  },




});

const mapStateToProps = state => {
  return {
    user: state.user,
    isLoading: state.ui.isLoading,
    isAuthenticated: state.auth.authenticated,
    error: state.auth.error
  };
};

export default withNavigation(connect(mapStateToProps, null)(Rota));

这是当前返回数组的屏幕截图:

enter image description here

1 个答案:

答案 0 :(得分:0)

  

map()方法创建一个新数组,其结果是调用一个   在调用数组中的每个元素上提供了功能

因此,假设您的weekCommencingDates也是一个数组,则可以这样操作:

const dataList = this.props.user.weekCommencingDates.map(x => ({
  label: x.Text,
  value: x.Value
}))

对于数组的每个项x,它返回一个以labelvalue作为键的新对象