我有一个用View创建的自定义卡片元素,并且我想在一行上映射卡片元素双卡片,例如,数组在第一行中有4个元素2个卡片项目,其他行有2个卡片项目,因此每行根据双组视图到数组中的元素,我下面的代码是所有元素行
const cardView = () => {
cardItem = [
{title: 'Title1', value: 'val1'},
{title: 'Title2', value: 'val2'},
{title: 'Title3', value: 'val3'},
{title: 'Title4', value: 'val4'},
];
return (
<View style={{marginHorizontal:5}}>
<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
{cardItem.map((item, i) => {
return (
<View style={styles.cardInner}>
<Text text={item.title} />
<Text text={item.value} />
</View>
);
})}
</View>
</View>
);
};
答案 0 :(得分:1)
要获得所需的结果,您需要在父容器上定义flex-wrap样式,并将其设置为“ wrap”,然后为每个子元素提供半角宽度。这是一个片段
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
export default function App() {
const cardItem = [
{ title: 'Title1', value: 'val1' },
{ title: 'Title2', value: 'val2' },
{ title: 'Title3', value: 'val3' },
{ title: 'Title4', value: 'val4' },
];
return (
<View style={styles.container}>
{cardItem.map((item, i) => {
return (
<View style={styles.cardInner}>
<Text>{item.title}</Text>
<Text>{item.value}</Text>
</View>
);
})}
</View>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
width: '100%',
flexWrap: 'wrap',
padding: 8,
},
cardInner: {
width: '50%'
},
});
小吃:https://snack.expo.io/@saachitech/dcffc0
有关弹性盒和弹性包装物属性https://reactnative.dev/docs/flexbox#flex-wrap
的更多信息答案 1 :(得分:0)
就像使用react-native-grid-component一样解决类似问题。可以设置每行numColumns
的自定义元素数。
示例:
import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
import Grid from 'react-native-grid-component';
class Simple extends Component {
_renderItem = (data, i) => (
<View style={styles.cardInner}>
<Text text={item.title} />
<Text text={item.value} />
</View>
);
render() {
return (
<Grid
renderItem={this._renderItem}
data={[
{title: 'Title1', value: 'val1'},
{title: 'Title2', value: 'val2'},
{title: 'Title3', value: 'val3'},
{title: 'Title4', value: 'val4'},
]}
numColumns={2}
/>
);
}
}
const styles = StyleSheet.create({
...
});
答案 2 :(得分:0)
您可以这样做:
const cardView = () => {
cardItem = [
{ title: 'Title1', value: 'val1' },
{ title: 'Title2', value: 'val2' },
{ title: 'Title3', value: 'val3' },
{ title: 'Title4', value: 'val4' },
];
mappedCards = cardItem.map((item) => {
return (
<Text text={item.title} />
)
})
return (
<View style={{ marginHorizontal: 5 }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<View style={styles.cardInner}>
{mappedCards}
</View>
</View>
</View>
);
};