React Native如何实现height: auto效果 让图片占满视图宽度且不拉伸
React Native 图片宽度100%时高度自适应解决方案
问题场景
React Native开发中插入图片时,配置width: '100%'期望图片占满父容器全宽,但是仅当手动设置固定整数高度值时图片才能正常显示,无法实现类似Web端height: auto的自适应高度效果。
初始问题代码
const SplashScreen = () => { return ( <View style={styles.container}> <Text>Splash Screen</Text> <Image source={require('../assets/Login.png')} style={styles.logo} /> </View> ) } export default SplashScreen const styles = StyleSheet.create({ logo: { flex: 1, width: '100%', height: 300, resizeMode: 'contain', } }
可用修复方案
给父容器styles.container添加height: '100%'属性后,即可通过flex属性动态调整图片高度,无需硬编码固定高度值,调整后的图片样式如下:
logo: { flex: 0.5, width: '100%', resizeMode: 'contain', backgroundColor: 'red' }
可以根据实际布局需求调整flex的数值,控制图片占父容器高度的比例。
内容的提问来源于stack exchange,提问作者Prabodh
相关产品推荐
相关产品推荐

