gpt4 book ai didi

react-native - 如何通过保持宽高比来根据其宽度动态设置 View 高度?

转载 作者:行者123 更新时间:2023-12-03 14:30:07 32 4
gpt4 key购买 nike

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

我希望它的工作原理类似于以下代码:

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

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

在flexbox的react-native中这可能吗?

最佳答案

正如Hendy Irawan所评论的那样,React Native将aspectRatio属性添加到StyleSheet中。

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

从文档中:

aspectRatio?: number

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



因此,以下应工作:
const styles = StyleSheet.create({
view: {
aspectRatio: 1.5,
}
});

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

关于react-native - 如何通过保持宽高比来根据其宽度动态设置 View 高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37133897/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com