【问题标题】:react native how to loop View component in JSX反应原生如何在 JSX 中循环查看组件
【发布时间】:2018-05-24 07:37:48
【问题描述】:

我想做什么

我每行最多只能补5张优惠券,如果超过5张优惠券我会移动到下一行。

如果 couponNum == 5

O O O O O

如果 couponNum == 12

O O O O O

O O O O O

噢噢

代码

<View style={styles.couponBox}>

    {this.createCoupon(couponNum)}

</View>
  
const styles = StyleSheet.create({
  couponBox: {
      flex: 1, 
      flexDirection: 'row',
      // alignItems: 'center',
      alignSelf: 'center',
      justifyContent: 'center', 
      backgroundColor: 'yellow',
      width: width - 100,
      height: height -200, 
  },
  circle: {
      width: 44,
      height: 44,
      borderRadius: 44/2,
      backgroundColor: colors.lightFink,
      alignItems: 'center',
      justifyContent: 'center',
  },
})

createCoupon = (couponNum) => {
    let coupons = []
    let i = 1;

    while( i <= couponNum ) {
        let children = []
        children.push(
            <View>
                <View style={{width: 50, height: 50, margin: 5, }}>
                    <View style={styles.circle}>
                        <Text style={{fontSize: 16,  }}>{i}</Text>
                    </View>
                </View>

            </View>
        )
        table.push(<View style={{flex: 2, flexDirection: 'row', }}>{children}</View>)      

        i++;
    }
    return coupons
}

但是这个代码是这样的错误..

如果 couponNum == 5

O O O O O

如果 couponNum == 12

呜呜呜呜呜

我应该怎么做才能解决这个问题?

【问题讨论】:

  • 不要忘记在返回节点数组时添加key属性&lt;View key={somethingUniquePreferNotIndexIfPossible} ...&gt;

标签: javascript react-native ecmascript-6


【解决方案1】:

希望这对您的查询有所帮助。

createCoupon = (couponNum) => {
    let coupons = [];
    let rows = couponNum % 5 == 0 ? couponNum/5 : (couponNum/5) +1;
    rows = parseInt(rows);
    let num = 1;

    for (let i = 1; i <= rows; i++){
        let children = [];
        let cols = i < rows ? 5 : couponNum % 5 > 0 ? couponNum % 5 : 5;

        for(let j = 1; j<= cols ; j++){
            children.push(
                <View key={num++}>
                    <View style={{width: 50, height: 50, margin: 5, }}>
                        <View style={styles.circle}>
                            <Text style={{fontSize: 16,  }}>{num}</Text>
                        </View>
                    </View>
                </View>
            );
        }
        coupons.push(<View key={i} style={{flex: 2, flexDirection: 'row', }}>{children}</View>)
    }
    return coupons
}

【讨论】:

  • {num} 由于 View 键中的 num++ 而开始 2。我更新了'让 num = 0;'然后一切都做得很好!感谢您的回答!
【解决方案2】:

相信你可以通过简单的控制children的宽度来解决。

/** Multiply the with 1/5 and subtract 100 as parent width is also  
  * misused  with 100
  */

<View style={{width:  width * (1/5) - 100, height: 50, margin: 5, }}>
   <View style={styles.circle}>
      <Text style={{fontSize: 16,  }}>{i}</Text>
   </View>
</View>

【讨论】:

  • 这是为圈子的父视图而不是圈子本身
猜你喜欢
  • 1970-01-01
  • 2018-02-02
  • 2018-05-16
  • 1970-01-01
  • 2021-05-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 2018-09-11
相关资源
最近更新 更多