首页 > 解决方案 > How to make a View Parent Component resize to fit child image component

问题描述

Having trouble making a parent view resize to just fit its child components one of which is an Image component that will change its width to match the screen width and then the height should simply be whatever necessary to conserve aspect ratio of the image.

cardContainer refers to the Card that will house mulitple components and should resize height in order to fit components. postMedia refers to styling for an image that will fill the width of the screen but the height will be unknown (want this to be done dynamically to conserve aspect ratio without distortion or cropping. mediaContainer is the container for the image which will resize according to the necessary height to fit the image and is one of several components inside the Card.

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
    }
});

I've tried setting the child components to flex: 1 but that results in the views filling the entire screen which I don't want. I only want to have the cardContainer just large enough to fit all content without stretching the entire screen.

The code that works for just one image that I'm working with is below:

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
    }
});

I just need to find a way for the view to use the height that fits the image instead of hard coding as above.

标签: reactjsreact-nativelayoutviewflexbox

解决方案


react-native-scalable-image library solved my issue. The library dynamically finds the height to conserve the aspect ration of image.


推荐阅读