如何解决React Native:图像未显示
请告诉我有什么问题。
import React from 'react';
import { StyleSheet,Text,View,Image } from 'react-native';
export default function App() {
return (
<View>
<Image
style={styles.backgroundImage}
source={require('./assets/bg.jpg')}
/>
</View>
);
}
const styles = StyleSheet.create({
backgroundImage: {
height: '100%',width: undefined,aspectRatio: 1,zIndex: 1,},});
它只是显示白屏。没有别的。
解决方法
react-native 图像组件需要按像素设置大小。
因此,您的第一个解决方案是获取屏幕/窗口的尺寸并相应地设置宽度和高度。所以你需要使用纵横比来计算。您还可以使用“拉伸”、“包含”、“覆盖”等调整大小模式,如here
所述import React from "react";
import { Image,StyleSheet,View,Dimensions} from "react-native";
const dimensions = Dimensions.get('window');
const imageHeight = Math.round(dimensions.width * 9 / 16); //calculate with aspect ratio
const imageWidth = dimensions.width;
function App() {
return (
<View>
<Image
style={styles.backgroundImage}
source={require('./assets/bg.jpg')}
/>
</View>
);
}
const styles = StyleSheet.create({
backgroundImage: {
height: imageHeight,width: imageWidth,zIndex: 1,},});
export default App;
第二种解决方案: 因为您似乎想将其设置为背景图像,所以使用 here
中所述的 BackgroundImage 组件function App() {
return (
<ImageBackground style={styles.backgroundImage} source={require('./assets/bg.jpg')} />
);
}
const styles = StyleSheet.create({
backgroundImage: {
height: '100%',width: undefined,aspectRatio: 1,}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。