如何通过保持宽高比来根据其宽度动态设置视图高度? [英] How to dynamically set height of view based on its width by keeping aspect ratio?

查看:70
本文介绍了如何通过保持宽高比来根据其宽度动态设置视图高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个视图,该视图的宽度响应于其容器宽度,同时保持其宽高比. 我不想对宽度或高度进行硬编码,但要使其保持动态和响应性,以便可以在多种情况下将其作为可重用的组件进行重用.

I want to have a view whose width is responsive to its container width while keeping its aspect ratio. I don't want to hard code width or height, but keep it dynamic and responsive so that it can be reused in multiple situations as a reusable component.

我希望它的工作方式类似于以下代码:

I hope it works similar to the following code:

<View style={{
  alignSelf: 'stretch',
  aspectRatio: 1.5
}} />

它应该填充容器的宽度,并根据其宽度动态设置其自身的高度.

It should fill its container's width and set its own height dynamically based on its width.

在flexbox的本机版本中有可能吗?

Is this possible in react-native with flexbox?

推荐答案

正如Hendy Irawan所说,React Native将aspectRatio属性添加到了StyleSheet.

As Hendy Irawan commented, React Native added aspectRatio property to StyleSheet.

https://facebook.github.io/react- native/docs/layout-props.html#aspectratio

从文档中:

aspectRatio ?:数字

aspectRatio?: number

纵横比控制节点的未定义尺寸的大小. 长宽比是非标准属性,仅在本机中可用 而不是CSS.

Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a non-standard property only available in react native and not CSS.

在设置了宽/高宽高比的节点上,控制 未设置尺寸在具有设置的伸缩基础高宽比控件的节点上 如果未设置,则节点在横轴上的大小在具有 测量功能的宽高比就像测量功能一样工作 在具有弹性增长/收缩纵横比的节点上测量弹性 如果未设置纵横比,则控制节点在横轴上的大小 考虑最小/最大尺寸

On a node with a set width/height aspect ratio control the size of the unset dimension On a node with a set flex basis aspect ratio controls the size of the node in the cross axis if unset On a node with a measure function aspect ratio works as though the measure function measures the flex basis On a node with flex grow/shrink aspect ratio controls the size of the node in the cross axis if unset Aspect ratio takes min/max dimensions into account

因此,以下内容应该起作用:

Thus the following should work:

const styles = StyleSheet.create({
  view: {
    aspectRatio: 1.5,
  }
});

// later in render()
<View style={styles.view} />

这篇关于如何通过保持宽高比来根据其宽度动态设置视图高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆