简体   繁体   English

React Native:适合容器中的正方形

[英]React Native: fit square in container

I have the following code:我有以下代码:

import React from "react";
import { StyleSheet, View } from "react-native";

function App() {
  return (
    <View style={styles.container}>
      <View style={styles.row_1}>
        <View style={styles.square} />
      </View>
      <View style={styles.row_2}>
        <View style={styles.square} />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  row_1: {
    flex: 1,
    backgroundColor: "red",
    alignItems: "center",
    padding: 10
  },
  row_2: {
    flex: 5,
    backgroundColor: "blue",
    alignItems: "center",
    //flexDirection: 'row',
    padding: 10
  },
  square: {
    flex: 1,
    aspectRatio: 1,
    backgroundColor: "white"
  }
});

export default App;

I'm trying to insert a white square in the center of the rows, without knowing a priori the height and the width of the rows.我试图在行的中心插入一个白色方块,但事先不知道行的高度和宽度。 In the example, on a 4:3 phone, the first row is larger then higher and the second row higher than larger.在示例中,在 4:3 手机上,第一行先大后高,第二行先高后大。

The square in the first row is correct, but the square in the second row exceeds the margins.第一行的方格是正确的,但是第二行的方格超出了边距。 I can manually set flexDirection: 'row' in the row_2 to achieve the expected result, but just because I know the container is higher than larger.我可以在 row_2 中手动设置 flexDirection: 'row' 来达到预期的结果,但这只是因为我知道容器是高而不是大。 How can I achieve the same result, without specifing the flex direction?如何在不指定弯曲方向的情况下获得相同的结果?

Sandbox here沙盒在这里

Not exactly sure what the final result you're looking for, but for something responsive like this I would consider using a dynamic unit on width/height properties on your squares like viewport units -- vw, vh, vmin, vmax.不确定您要寻找的最终结果是什么,但是对于像这样的响应式的东西,我会考虑在您的正方形上使用宽度/高度属性的动态单位,例如视口单位——vw、vh、vmin、vmax。

Alternatively you can get the viewport dimensions in pixels:或者,您可以获得以像素为单位的视口尺寸:

//e.g.

 document.documentElement.clientWidth
 document.documentElement.clientHeight

//or including scrollbar:
 window.innerWidth
 window.innerWidth

Then use a css styles library like emotion use the viewport dimensions in your styles.然后使用 css styles 库,例如emotion使用 styles 中的视口尺寸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM