javascript - 在反应本机应用程序中动态填充网格内的行和列
问题描述
我正在开发一个反应本机应用程序,我想用来自服务器的输入动态填充我的网格布局,我希望结果是那种形状:
<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 列),我想创建一个函数来获取来自服务器的所有输入并呈现类似于我硬编码的内容。
解决方案
首先,您需要获取数据的形状以反映网格:
// 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>
推荐阅读
- mongodb - 调用mongo存储库的保存方法时未调用Mongo Date Custom Converter
- csv - Neo4j 导入 CSV 文件(neo.TransientError.General.OutOfMemoryError)
- java - Jackson 可以解析不是 ISO-8601 的日期时间值吗?
- java - 使用OkHttp时Webapp卸载内存泄漏,是否误报?
- mariadb - 使用机器的外部 IP 地址时无法连接到数据库
- java - 我需要从线程返回一些东西
- python-3.x - 如何找到索引为时间戳的每小时的多个斜率?
- scala - 如何将 DF 转换为字符串/数组,然后再转换回 DF?
- java - 使用 Java 检查 Spark Dataframe 中是否存在列
- centos - fio测量RAID0虚拟磁盘的IO速度混淆结果