【问题标题】:How to make a View Parent Component resize to fit child image component如何使视图父组件调整大小以适合子图像组件
【发布时间】:2020-01-27 00:00:06
【问题描述】:

无法调整父视图的大小以适合其子组件,其中一个是 Image 组件,该组件将更改其宽度以匹配屏幕宽度,然后高度应该只是保持图像纵横比所需的任何值。

cardContainer 是指将容纳多个组件并应调整高度以适应组件的卡。 postMedia 指的是图像的样式,它将填充屏幕的宽度但高度未知(希望动态完成以保持纵横比而不失真或裁剪。mediaContainer 是图像的容器,它将根据所需的高度调整大小以适合图像,并且是卡片内的几个组件之一。

const styles = StyleSheet.create({
    cardContainer: {
        backgroundColor: 'grey',
        width: '100%',
        height: undefined,
        borderTopWidth: 2,
        borderBottomWidth: 2,
        borderTopColor: 'black',
        flex: 0,
        flexShrink: 1
    },
    postMedia: {
        resizeMode: 'contain',
        width: '100%',
        height: undefined
    },
    mediaContainer: {
        backgroundColor: 'green',
        flex: 0,
        flexShrink: 1
    }
});

我尝试将子组件设置为 flex: 1 但这会导致视图填满整个屏幕,这是我不想要的。我只想让cardContainer 大到足以容纳所有内容而不拉伸整个屏幕。

仅适用于我正在使用的一张图像的代码如下:

const styles = StyleSheet.create({
    cardContainer: {
        backgroundColor: 'grey',
        width: '100%',
        height: undefined,
        borderTopWidth: 2,
        borderBottomWidth: 2,
        borderTopColor: 'black',
        flex: 0,
        flexShrink: 1
    },
    postMedia: {
        resizeMode: 'contain',
        width: '100%',
        height: 233
    },
    mediaContainer: {
        backgroundColor: 'green',
        flex: 0,
        flexShrink: 1
    }
});

我只需要找到一种方法让视图使用适合图像的高度,而不是像上面那样硬编码。

【问题讨论】:

  • 确实找到了一个名为react-native-scalable-image 的第三方库,它通过动态查找高度以节省图像的纵横比来解决我的问题。但仍然很好奇是否有办法使用默认的 React Native 样式来做到这一点。

标签: reactjs react-native layout view flexbox


【解决方案1】:

react-native-scalable-image 库解决了我的问题。库动态查找高度以保持图像的纵横比。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-19
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多