我有一个包含 5 个元素的数组:
[
{
"id": 1,
"title": "Title 1",
"description": "descriptions"
},
{
"id": 2,
"title": "Title 1",
"description": "descriptions"
},
{
"id": 3,
"title": "Title 1",
"description": "descriptions"
},
{
"id": 4,
"title": "Title 1",
"description": "descriptions"
},
{
"id": 5,
"title": "Title 1",
"description": "descriptions"
}
]
我希望它们显示如下:
<Item>
<Text style={styles.cardText}>Title 1</Text>
<Text style={styles.cardText} numberOfLines={2}>Description 1</Text>
</Item>
<Grid>
<Col>
<Item>
<Text style={styles.cardText}>Title 2</Text>
<Text style={styles.cardText} numberOfLines={2}>Description 2</Text>
</Item>
</Col>
<Col>
<Item>
<Text style={styles.cardText}>Title 3</Text>
<Text style={styles.cardText} numberOfLines={2}>Description 3</Text>
</Item>
</Col>
</Grid>
<Grid>
<Col>
<Item>
<Text style={styles.cardText}>Title 4</Text>
<Text style={styles.cardText} numberOfLines={2}>Description 4</Text>
</Item>
</Col>
<Col>
<Item>
<Text style={styles.cardText}>Title 5</Text>
<Text style={styles.cardText} numberOfLines={2}>Description 5</Text>
</Item>
</Col>
</Grid>
如何在 React Native 中显示上述内容?
我尝试使用datas.map功能,但不能。我试图添加字符串,但我认为这不是解决方案。
有解决方案吗?
谢谢大家。
您可以将array
chunk
为 0 以外的索引分成 2 个部分。
constructor() {
super();
this.state = {
data: [
{
"id": 1,
"title": "Title 1",
"description": "descriptions"
},
{
"id": 2,
"title": "Title 1",
"description": "descriptions"
},
{
"id": 3,
"title": "Title 1",
"description": "descriptions"
},
{
"id": 4,
"title": "Title 1",
"description": "descriptions"
},
{
"id": 5,
"title": "Title 1",
"description": "descriptions"
}
],
chunk: this.chunk
}
}
分块array
的方法:
chunk(array, chunkSize) {
return [].concat.apply([],
array.map(function (elem, i) {
return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
})
);
};
渲染项目:
render() {
let { data, chunk } = this.state;
let dataForChunk = [...data];
dataForChunk.splice(0, 1); //removes 1st index of array
let chunkedArr = chunk(dataForChunk, 2);
return (<View style={{flex: 1}}>
<Item>
<Text style={styles.cardText}> {data[0].title} </Text>
<Text style={styles.cardText} numberOfLines={2} > {data[0].description} </Text>
</Item>
{chunkedArr.map((arr, index) => {
return(
<Grid>
{arr.map(item => {
return(
<Col>
<Item>
<Text style={styles.cardText} >{item.id}</Text>
<Text style={styles.cardText} numberOfLines={2}>{item.description}</Text>
</Item>
</Col>
);
})}
</Grid>
)
})}
</View>)
}
您可以改用 FlatList。
考虑示例
const row = [{key: 'a'}, {key: 'b'}]
平面列表用法:
<FlatList
data={row}
renderItem={(item) => this._renderItem(item)}
keyExtractor={extractKey}
extraData={row}
/>
内部渲染视图功能:
_renderItem = ({item}) => {
return <Text>{item.key}</Text>
}