纵横比在兄弟元素之间造成间隙

问题描述 投票:0回答:1

我有一个二维数组,呈现一个正方形网格。网格应该是一个正方形,并且每个正方形都应该是一个正方形,如aspectRatio 为1。

基本网格如下所示:

    <View>
      <View style={styles.container}>
        {board.map((row, i) => {
          return (
            <View key={i} style={styles.row}>
              {row.map((square, j) => {
                return <View style={styles.square}>{square}</View>
              })}
            </View>
          );
        })}
      </View>
    </View>


const getStyles = (dimension: number) => {
  return StyleSheet.create({
    container: {
      width: "100%",
    },
    row: {
      flexDirection: "row",
      gap: 4,
      marginBottom: 4,
      width: "100%",
    },
    square: {
      flex: 1,
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
      aspectRatio: 1,
    }
  });
};

This code renders a correct grid of squares. The gap and margin create the illusion of borders but this way there are no borders on the sides of the page.

The issue is that depending on the size of the grid, 5x5, 6x6, etc, there will be random gaps between rows. It's almost as if the math doesn't check out, like the screen width mixed with the amount of squares/columns/rows and the gap/margin size is making it impossible to render perfect squares.

Is that possible? Is there a way to figure out the perfect aspect ratio to render squares while extending the full width of the screen? I feel like it should be possible or there should be a way to make the aspect ratio fill up available space. 

I don't mind if the squares aren't perfect as long as there are no unwanted gaps between rows or columns and as long as the grid covers the full width of the screen.

react-native aspect-ratio
1个回答
0
投票

尚不清楚问题是什么,但如果您希望水平排列行中的项目,则可能需要将

display: flex
添加到行中。 (这也可能是默认设置/不适用于本机反应。)

.container {
  width: 100%;
}

.row {
  display: flex; /* missing display: flex */
  gap: 4px;
  margin-bottom: 4px;
}

.square {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  aspect-ratio: 1;
  background: aliceblue;
}
<div class="container">
  <div class="row">
    <div class="square">{square}</div>
    <div class="square">{square}</div>
    <div class="square">{square}</div>
    <div class="square">{square}</div>
  </div>
  <div class="row">
    <div class="square">{square}</div>
    <div class="square">{square}</div>
    <div class="square">{square}</div>
    <div class="square">{square}</div>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.