反应本机:使用array.map渲染

时间:2020-01-04 18:01:40

标签: arrays reactjs native

我正在尝试使用array.map,但无法看到结果。请帮忙。

我正在尝试创建一个像单元格一样的日历,下面的代码将不会显示任何错误或任何内容。

仅迭代两个数组即可得到结果。但它行不通。我对本地初学者很反感

import React, { Component } from 'react';
import { View, StyleSheet, Text } from 'react-native';

export default class LearnMap extends React.Component {
    constructor(props) {    
        super(props);
      
      }
     

  render() {
    var rows = [0,1,2,3,4,5,6];
    var cols = [
      ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
      [1,2,3,4,5,6,7],
      [8,9,10,11,12,13,14],
      [15,16,17,18,19,20,21],
      [22,23,24,25,26,27,28],
      [29,30,31,1,2,3,4],
      [5,6,7,8,9,10,11],    
    ];
  
    return(<View style={‌{flex:1,justifyContent:'center', alignItems:'center'}}>
    { rows.map((row, rowIndex)=>{ 

        <View key={rowIndex} style={styles.row}>         
      {   cols[row].map((col, colIndex)=>{
        <View key={colIndex} style={styles.cell}><Text key={colIndex}>{col.toString}</Text></View>
        })
      }
        </View>

    })
  }
    </View> );
  }
}
const styles = StyleSheet.create({
  container: {
      
  },
  row:{
    flexDirection:'row',
    marginLeft:10,
    marginRight:10,    
  },
  cell:
  {
    flex:1, 
    backgroundColor:'pink', 
    alignItems:'center', 
    justifyContent:'center', 
    height:45, 
    borderWidth:1, borderColor:'black'
  }


});

2 个答案:

答案 0 :(得分:0)

您需要在return函数中添加map

您在地图函数中返回的内容将被渲染。在您的情况下,您想这样做:

rows.map((row, rowIndex)=> { 

   return (
          <View key={rowIndex} style={styles.row}>         
              {   
                  cols[row].map((col, colIndex)=> {
                      return <View key={colIndex} style={styles.cell}><Text key={colIndex}>{col.toString}</Text></View>
                  })
              }
          </View>
          )

    })

注意:您在两个地图功能中都忘记了它,因此您需要像上面的示例一样在两者中添加它。

答案 1 :(得分:0)

我自己解决了。只需放置一个return语句

 return <View style={{flex:1,justifyContent:'center', alignItems:'center'}}>
      { rows.map((row, rowIndex)=> { 
        return <View style={styles.row} key={rowIndex}>
            { cols[row].map((col, colIndex)=> {
                       return <View key={colIndex} style={styles.cell}>
                         <Text key={colIndex}> {col} </Text>
                         </View>

                     })
            }
            </View>
       })
      }
    </View>