[英]React Native - Map elements two on a row
I have an array of objects in React Native.我在 React Native 中有一组对象。 What is the simplest way to map them two on a row like in the following picture: map 最简单的方法是把它们两个放在一行中,如下图所示:
https://i.stack.imgur.com/VGWTr.png https://i.stack.imgur.com/VGWTr.png
I have a function that converts an array into an array of arrays of 2 elements:我有一个 function 将一个数组转换为一个包含 2 个元素的 arrays 数组:
{/* Example input: [0, 1, 2, 3, 4, 5, 6, 7] */}
{/* Example output: [ [0, 1] , [2, 3] , [4, 5] , [6, 7] ] */}
then simply map each element into a View that contains two other View elements, but seems way too overkill.然后简单地将 map 每个元素放入一个包含其他两个 View 元素的 View 中,但似乎太过分了。
Is there a simpler method?有没有更简单的方法?
yes, there is a simpler way.是的,有一个更简单的方法。 You could set width 50% to each element and to the parent set flexDirection: 'row' and flexWrap: 'wrap'您可以为每个元素和父集 flexDirection: 'row' 和 flexWrap: 'wrap' 设置宽度 50%
Instead of map, the Better way is to Use FlatList
with prop numColumns={2}
而不是 map,更好的方法是使用FlatList
与 prop numColumns={2}
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
numColumns={2}
/>
Full Example:完整示例:
Working Demo: Expo Snack工作演示: Expo 小吃
Output: Output:
Source Code:源代码:
import * as React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';
const list = [0, 1, 2, 3, 4, 5, 6, 7];
export default function App() {
return (
<View style={styles.container}>
<FlatList
data={list}
numColumns={2}
keyExtractor={(item)=> item}
renderItem={({ item }) => (
<View style={styles.card}>
<Text style={styles.text}>{item}</Text>
</View>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
card: {
height: 100,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#212121',
boxShadow: "10px 10px 0px -5px rgba(209,25,209,1)",
margin: 5,
borderRadius: 10,
},
text: {
fontSize: 40,
fontWeight: '600',
color: 'white',
},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.