我正在学习React Native,并且在显示ImageBackground组件时遇到问题。ImageBackground的源指向同一文件夹中的图像,尽管这仍然不可见,除非我给ImageBackgrounds一个数字高度,因为如果我试图给它一个%的高度,它仍然不会显示出来。以下是执行样式的组件的代码:
import React from 'react';
import { View, ImageBackground, StyleSheet, Text } from 'react-native';
export default function WelcomeScreen(props) {
return (
<View>
<Text>Welcome</Text>
<ImageBackground source={require('./background.jpg')} style={styles.background} />
</View>
);
}
尝试不同的风格,ImageBackground在显示自己方面有不同的行为:
这不会显示ImageBackground:
const styles = StyleSheet.create({
background: {
flex: 1,
},
});
这也不会:
const styles = StyleSheet.create({
background: {
flex: 1,
height: '100%',
},
});
这将显示:
const styles = StyleSheet.create({
background: {
flex: 1,
height: 300,
},
});
我不明白为什么会发生这种事。根据我的理解,只有当图像来自网络时,才应该添加大小,不管怎样,%值应该仍然有效。我在这里错过了什么?
编辑:我使用Dimension并将屏幕高度输入ImageBackground:来解决这个问题
import { View, ImageBackground, StyleSheet, Dimensions } from 'react-native';
const { height } = Dimensions.get('screen');
const styles = StyleSheet.create({
background: {
flex: 1,
height,
},
});
尽管它有效,但为什么我需要为同一文件夹中的图像设置高度的问题仍然存在。
如果你想在这种情况下给出一个百分比值,你应该使用一些技巧,比如:
background: {
height: deviceHeight,
},
container: {
height: deviceHeight * 50 / 100,
}
或者,您可以以react native responsible screen的名义使用一个流行的库。这个库将使您能够在场景后面给出相对值并将其转换为绝对值。下面的片段将展示如何使用它:
import {widthPercentageToDP, heightPercentageToDP} from 'react-native-responsive-screen';
const styles = StyleSheet.create({
background: {
height: heightPercentageToDP('100%'),
}
})
这应该如您所期望的那样工作;(
如果你想让背景图像覆盖整个视图,可以试试这样的方法:
<View>
<ImageBackground style={styles.image} resizeMode={'cover'} source={require('../Images/test.jpg')}>
{/*your components*/}
</ImageBackground>
</View>
采用这种样式:
const styles = StyleSheet.create({
image: {
height: '100%',
width: undefined,
}
})