【问题标题】:Why isn't react native displaying my background image?为什么反应原生不显示我的背景图片?
【发布时间】:2018-11-07 06:19:51
【问题描述】:

下面的代码可以很好地编译为 react native,并且我在任何编译器中都没有收到任何错误,但我的 android 模拟器保持空白,而不是像预期的那样显示背景图像。有谁知道为什么?

代码:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ImageBackground} from 'react-native';

import bgImage from './Images/background.jpg' 

type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View>
      <ImageBackground source={bgImage} style={styles.backgroundContainer}>
      </ImageBackground>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    backgroundContainer: {
    flex: 1,
    width:null, 
    height:null, 
    justifyContent: 'center',
    alignItems: 'center',
  },
});

【问题讨论】:

  • 试试&lt;ImageBackground soure={require('./Images/background.jpg' )} style={styles.backgroundContainer}&gt;
  • 接受他的答案...不要只回答问题,即使它已经有了答案...
  • 这里很晚,但注意到代码上有一个错字。它应该是 source={bgImage} 而不是 soure={bgImage}

标签: android ios react-native compiler-errors cross-platform


【解决方案1】:

试试这个方法

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ImageBackground} from 'react-native';

type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View>
      <ImageBackground source={require(./Images/background.jpg)} style={styles.backgroundContainer}>
          <Text> Here Background Image </Text>
      </ImageBackground>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    backgroundContainer: {
    flex: 1,
    width:'100%', 
    height:'100%',
  },
});

【讨论】:

    【解决方案2】:

    你应该使用require

     <ImageBackground soure={require(bgImage)} style={styles.backgroundContainer}>
          </ImageBackground>
    

    【讨论】:

    • 我实际尝试过,但没有成功。我收到一条错误消息:“捆绑失败:错误:App.js:Invalid call at line 19: require(_background.default)”。
    • 什么是_background.default?你应该使用 require(bgImage)
    【解决方案3】:

    source={require(BgIMage)}你错过了require

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 2021-08-03
      • 2023-04-07
      • 2018-05-04
      相关资源
      最近更新 更多