#javascript #react-native
#javascript #react-native
Вопрос:
Я работаю над приложением react native, я хочу динамически заполнять свой макет сетки входными данными с сервера, я хочу, чтобы результат был в этой форме :
<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 столбца), я хочу создать функцию, которая принимает все входные данные с сервера и отображает что-то вроде того, что я жестко запрограммировал.
Ответ №1:
Во-первых, вам нужно получить форму ваших данных, чтобы отразить сетку:
// 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>