本机如何在JSX中循环View组件

时间:2018-05-24 07:37:49

标签: javascript react-native ecmascript-6

我想做什么

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

如果couponNum == 5

O O O O O

如果couponNum == 12

O O 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
}
&#13;
&#13;
&#13;

但是这段代码有点错误......

如果couponNum == 5

O O O O O

如果couponNum == 12

OOOOOOOOOOOO

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

2 个答案:

答案 0 :(得分:2)

希望这可以帮助您查询。

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
}

答案 1 :(得分:0)

我相信你可以通过简单地控制孩子的宽度来解决。

/** 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>