javascript - React-Native - 创建网格

标签 javascript react-native

以下代码生成一行 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/

相关文章:

php - 使用 php/mysql 在 googlemaps 上动态绘制折线

javascript - Uncaught Error : [$injector:modulerr] In Firebase Authentication

react-native - 在 iOS 上未收到本地预定通知

java - 安装额外的 Java 依赖项到 React-Native 库

javascript - 数据格式化问题 : Array to Object. 有什么简单的方法吗?

javascript - 编译动态内容 - AngularJS

javascript - 如何在打开第二个屏幕后关闭第一个屏幕

react-native - 如何在 native react 中从父 View 组件向所有子组件添加填充/边距?

javascript - 从数组 : react 渲染表格行

javascript - 一种格式化长压缩 JavaScript 代码的工具 (jCarousel)