【问题标题】:react native: rendering with array.map反应原生:使用 array.map 渲染
【发布时间】:2020-04-22 21:27:40
【问题描述】:

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

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

只需遍历两个数组即可获得结果。但它不会工作。我是 React Native 初学者

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'
  }


});

【问题讨论】:

  • 你在rows.map()忘记了return

标签: arrays reactjs native


【解决方案1】:

我自己解决了。只需放置一个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>

【讨论】:

    【解决方案2】:

    您需要在map 函数中添加return

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

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

    注意:您在两个地图函数中都忘记了它,因此您需要像上面的示例一样将其添加到两个函数中。

    【讨论】:

    • 这在cmets中已经提到了,为什么要发布它作为答案?
    猜你喜欢
    • 2022-11-12
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2020-06-29
    • 2019-07-31
    • 2019-08-09
    • 1970-01-01
    相关资源
    最近更新 更多