React Native图片样式不生效求助:StyleSheet设置无效需内联样式
React Native图片通过StyleSheet设置样式不显示的解决方案
你的问题出在StyleSheet结构错误:你把image样式嵌套在了container样式内部,导致styles.image这个引用无法访问到对应的样式规则,图片没有获得宽高属性,因此无法正常显示。
错误代码的问题点
原StyleSheet中,image是container的子属性,而非独立的顶级样式:
const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', // 错误:image样式嵌套在container内部,无法通过styles.image访问 image: { width: 100, height: 100, }, restaurantContainer: { width: "100%", }, }, });
修正后的代码
将image和restaurantContainer提升为StyleSheet的顶级样式规则,与container同级:
import { StatusBar } from 'expo-status-bar'; import {StyleSheet, Text, View, Image } from 'react-native'; export default function App() { return ( <View style={styles.container}> <View style={styles.restaurantContainer}> <Image source = {{ uri:"http://pngimg.com/uploads/google/google_PNG19632.png" }} style = { styles.image } /> </View> <StatusBar style="auto" /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, // 正确:独立的顶级样式规则 image: { width: 100, height: 100, }, restaurantContainer: { width: "100%", }, });
关键说明
React Native的StyleSheet.create()要求每个独立样式都是顶级键值对,不支持嵌套定义。内联样式能生效是因为直接给Image传递了合法的样式对象,而嵌套的StyleSheet规则无法通过styles.xxx的方式被访问到。
内容的提问来源于stack exchange,提问作者mcdoodle
相关产品推荐
相关产品推荐

