【问题标题】:How to make a 3 column - 4 row layout of responsive squares?如何制作响应式正方形的 3 列 - 4 行布局?
【发布时间】:2022-01-21 19:45:00
【问题描述】:

我想创建一个独立于设备的 3x4 方格布局。这些方块的容器<View> 的宽度/高度未知。我希望方块变大以填满可用的容器。

容器代码:

squaresContainer: {
    alignSelf: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    flex: 1,
    marginHorizontal: 15
}

还有“正方形”(目前不是正方形),使用 33% 的 flexBasis 来获得 3 列。总有 12 个方格,所以四行应该总是出现。

square: {
    alignItems: 'center',
    justifyContent: 'center',
    flexGrow: 1,
    flexShrink: 0,
    flexBasis: '33%'
}

【问题讨论】:

    标签: react-native flexbox react-native-stylesheet


    【解决方案1】:

    实际上,flex-box 只处理一个轴,因此您不能使用它来控制行和列。但是您可以通过在父视图中包装每 4 个视图来实现上述内容。例如:

    import React, { useState } from "react";
    import { View } from "react-native";
    
    const Square = ({ backgroundColor }) => {
      const [height, setHeight] = useState(0);
      return (
        <View
          onLayout={(e) => setHeight(e.nativeEvent.layout.width)}
          style={{ flex: 1, height, backgroundColor }}
        />
      );
    };
    
    export default function App() {
      return (
        <View style={{ flexDirection: "column" }}>
          <View style={{ flex: 1, flexDirection: "row" }}>
            <Square backgroundColor="red" />
            <Square backgroundColor="pink" />
            <Square backgroundColor="orange" />
            <Square backgroundColor="green" />
          </View>
          <View style={{ flex: 1, flexDirection: "row" }}>
            <Square backgroundColor="lightgreen" />
            <Square backgroundColor="yellow" />
            <Square backgroundColor="blue" />
            <Square backgroundColor="lightblue" />
          </View>
          <View style={{ flex: 1, flexDirection: "row" }}>
            <Square backgroundColor="skyblue" />
            <Square backgroundColor="brown" />
            <Square backgroundColor="gray" />
            <Square backgroundColor="red" />
          </View>
        </View>
      );
    }
    

    或者通过使用外部库来支持网格:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-20
    • 2019-12-18
    • 2014-06-21
    • 1970-01-01
    • 2019-06-16
    • 2018-03-19
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多