【问题标题】:Is there any better way to make same gap spaces between items in flex display?有没有更好的方法在弹性显示中的项目之间制作相同的间隙空间?
【发布时间】:2020-06-08 18:25:14
【问题描述】:
  1. 使用flexbox(因为它是react-native)
  2. 父容器的宽度是一个百分比
  3. 项目数可以是 4/5/6/7..
  4. 项目之间的间距相同
  5. 如下图所示

这是我的代码:

const styles = {
container: {
  width: screenWidth * 0.9,
  flexWrap: 'wrap',
  flexDirection: 'row'
},
item: {
  backgroundColor: 'red',
  height: 120,
  width: (width * 0.9 - 20) / 3,
  marginBottom: 10
}
}

<View style={styles.container}>
  {items.map((item, idx) =>
    <View style={[styles.item, { marginHorizontal: idx % 3 === 1 ? 10 : 0}]} />
  )}
</View>

还有其他更好的方法来实现这种布局吗?

【问题讨论】:

  • 你试过justifyContent: 'space-between'吗?
  • @AkhilAravind 不,你可以考虑有 5 项。
  • @MayankPandav 这也是一个选项。但首先我需要将数组分成三份。
  • 您已经根据条件拆分了 3 个数组

标签: css reactjs react-native flexbox


【解决方案1】:

请查看此演示: https://snack.expo.io/@immynk/demo

根据需要的高度宽度,您可以在 Flatlist 内的 View 组件中使用,也可以根据需要放置 numColumns

import * as React from 'react';
import { Text, View, StyleSheet, FlatList, Dimensions } from 'react-native';
import Constants from 'expo-constants';

const DATA = [
  {
    key: 1,
  },
  {
    key: 2,
  },
  {
    key: 3,
  },
  {
    key: 4,
  },
  {
    key: 5,
  },
  {
    key: 6,
  },
];

export default class App extends React.Component {
  render() {
    return (
      <View>
        <FlatList
          showsVerticalScrollIndicator={false}
          data={DATA}
          numColumns={3}
          renderItem={({ item, index }) => {
            return (
              <View
                style={{
                     backgroundColor: "red",
                    paddingHorizontal: 5,
                    paddingVertical: 5,
                    flexDirection: "row",
                    height:130,
                    width:130

                }}>
               <View style={{backgroundColor:"white",width:"100%"}}>

                </View>

              </View>
            );
          }}
          keyExtractor={item => item.key}
        />
      </View>
    );
  }
}

【讨论】:

  • 是处理列的最佳方式
猜你喜欢
  • 2017-04-14
  • 2017-12-21
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 2017-05-28
相关资源
最近更新 更多