以下代码生成一行 10 个正方形,其中包含随机数。我试图以某种方式使其成为 10 行 x 10 列的网格,但我被困在这里。我想将一行中的列限制为 10。因此,如果 var 限制为 40,它将创建 4 行 x 10 列。 60 将创建 6 行 x 10 列,等等。
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);
最佳答案
为其他偶然发现此帖子的人发布快速答案。
您可以简单地使用外部容器来限制宽度,以便子方 block
在填满整行后将被强制进入下一行。
外容器渲染函数
<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 .
关于javascript - React-Native - 创建网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946390/