首页 > 解决方案 > 在反应本机应用程序中动态填充网格内的行和列

问题描述

我正在开发一个反应本机应用程序,我想用来自服务器的输入动态填充我的网格布局,我希望结果是那种形状:

 <Grid>
        <Row>
          <Col
            style={{ backgroundColor: colors.dark_orange, height: h(30) }}
          >
          </Col>
          <Col
            style={{ backgroundColor: colors.green, height: h(30) }}
          ></Col>
          <Col
            style={{ backgroundColor: colors.gris, height: h(30) }}
          ></Col>
        </Row>
        <Row>
          <Col
            style={{ backgroundColor: colors.orange, height: h(30) }}
          ></Col>
          <Col
            style={{ backgroundColor: colors.purple, height: h(30) }}
          ></Col>
          <Col style={{ backgroundColor: colors.red, height: h(30) }}></Col>
        </Row>
        <Row>
          <Col
            style={{ backgroundColor: colors.transparent, height: h(30) }}
          ></Col>
          <Col
            style={{ backgroundColor: colors.white, height: h(30) }}
          ></Col>
          <Col
            style={{ backgroundColor: colors.green, height: h(30) }}
          ></Col>
        </Row>
        <Row>
          <Col
            style={{ backgroundColor: colors.dark_orange, height: h(30) }}
          ></Col>
          <Col
            style={{ backgroundColor: colors.green, height: h(30) }}
          ></Col>
          <Col
            style={{ backgroundColor: colors.gris, height: h(30) }}
          ></Col>
        </Row>
        <Row>
          <Col
            style={{ backgroundColor: colors.transparent, height: h(30) }}
          ></Col>
          <Col
            style={{ backgroundColor: colors.white, height: h(30) }}
          ></Col>
          <Col
            style={{ backgroundColor: colors.green, height: h(30) }}
          ></Col>
        </Row>
      </Grid>
    </ScrollView>
  </View>

正如您所看到的,我对输入和网格的形状进行了硬编码(每行有 3 列),我想创建一个函数来获取来自服务器的所有输入并呈现类似于我硬编码的内容。

标签: javascriptreact-native

解决方案


首先,您需要获取数据的形状以反映网格:

// Outer array represents rows, inner array represents columns
const grid = [
  [
    { backgroundColor: colors.dark_orange, height: h(30) },
    ...
  ], [
    ...
  ]
]

然后,只需使用类似.map的方法来遍历您的数据并返回相关的 JSX:

const renderRow = (row) => {
  return <Row>{row.map(renderCol)}</Row>;
}

const renderCol = (col) => {
  const { backgroundColor, height } = col;
  return <Col style={{ backgroundColor, height }}></Col>;
};

<Grid>{grid.map(renderRow)}</Grid>

推荐阅读