2017-01-30 49 views
0

以下代碼生成一行10個正方形,其中包含隨機數。我試圖以某種方式使它成爲10行10列的網格,但我卡在這裏。我想限制在一行中的列爲10.因此,如果var限制爲40,它會創建4行10列。 60會創建6行10列等React-Native - 創建網格

import React, { Component } from 'react'; 
import { View, Text, TouchableOpacity } from 'react-native'; 
import { connect } from 'react-redux'; 
import { Decrease, Increase, GetScore } from '../actions'; 
import { CardSection, Square } from './common'; 

class TableGenerator extends Component { 
    clickable(sq) { 
    this.props.Decrease(sq); 
    console.log(this.props.score); 
    } 

    generateRandom() { 
    // Random number generator 
    function* rand() { 
     while (true) { 
     yield Math.floor(Math.random() * 100) + 1; 
     } 
    } 
    const it = rand(); 
    const nums = []; 
    const limit = 10; 
    for (let i = 0; i < limit; i++) { 
     nums.push(it.next().value); 
    } 
    return nums.map((sq, i) => 
     <TouchableOpacity 
     key={i} 
     onPress={() => this.clickable(sq)} 
     > 
     <Square style={{ height: 30, width: 30 }}> 
      {nums[i]} 
     </Square> 
     </TouchableOpacity> 
    ); 
    } 

    render() { 
    return (
     <View> 
     <CardSection style={{ justifyContent: 'center' }}> 
      {this.generateRandom()} 
     </CardSection> 
     <CardSection> 
      <Text>Current Score: </Text> 
      <Text>{this.props.score}</Text> 
     </CardSection> 
     </View> 
    ); 
    } 
} 

const mapStateToProps = state => { 
    return { 
    score: state.scoreReducer 
    }; 
}; 

export default connect(mapStateToProps, { Decrease, Increase, GetScore })(TableGenerator); 
+1

我只是簡單地使用外部容器來限制寬度,並強制多餘的方塊到下一行。 –

+0

好的。謝謝。做了它並指定了flexWrap。 – Wasteland

+0

發佈了一個答案。我沒有使用flexWrap。但這並沒有太大的區別。 –

回答

1

發佈一個快速的答案爲其他人誰絆倒這個線程。

您可以簡單地使用一個外部容器來限制寬度,以便孩子square s在他們填滿整行後將被強制進入下一行。

在外部容器渲染功能

<Container style={width: '300px'}> 
    // iterate the and render the children squares 
</Container> 

square組件渲染功能

<Square style={width: '30px', height: '30px', float: 'left', display: 'inline-block'}> 
    // content 
</Square> 

我有發生在我的寵物項目類似的東西,你可以看到它在行動here