【问题标题】:Background Image wont appear in react native背景图像不会出现在本机反应中
【发布时间】:2021-05-10 03:24:18
【问题描述】:

我到处看了看,不知道为什么我的背景图像不工作路径很好,我已经尝试了一切,从将它包装在一个视图中,给它一个宽度和高度。它都不起作用。我是新手,所以我不知道这是一个常见的问题。登录按钮显示得很好,它纯粹是 bg 图像。 代码如下:

import React from "react";
import { ImageBackground, StyleSheet, Image, View } from "react-native";

function WelcomeScreen(props) {
  return (
    <View>
      <ImageBackground
        style={styles.background}
        source={require("../assets/background.jpg")}
      >
        <View style={styles.loginButton}></View>
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  background: {
    flex: 1,
  },
  loginButton: {
    width: "100%",
    height: 70,
    backgroundColor: "#fc5c65",
  },
});

【问题讨论】:

    标签: android ios react-native mobile


    【解决方案1】:
    import React from "react";
    import { ImageBackground, StyleSheet, Image, View } from "react-native";
    
    function WelcomeScreen(props) {
      return (
        <View style={styles.background}>
          <ImageBackground
            style={styles.background}
            source={require("../assets/background.jpg")}
          >
            <View style={styles.loginButton}></View>
          </ImageBackground>
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      background: {
        flex: 1,
      },
      loginButton: {
        width: "100%",
        height: 70,
        backgroundColor: "#fc5c65",
      },
    });
    

    【讨论】:

      【解决方案2】:

      向包含背景图像的视图添加样式似乎可行。如果其他人遇到此问题,请将您的代码更新为如下所示。

      import React from "react";
      import { ImageBackground, StyleSheet, Image, View } from "react-native";
      
      function WelcomeScreen(props) {
        return (
          <View style={styles.container}>
            <ImageBackground
              source={require("../assets/background.jpg")}
              style={styles.background}
            >
              <View style={styles.loginButton}></View>
            </ImageBackground>
          </View>
        );
      }
      
      const styles = StyleSheet.create({
        container: {
          flex: 1,
          flexDirection: "column",
        },
        background: {
          flex: 1,
          resizeMode: "cover",
        },
        loginButton: {
          width: "100%",
          height: 70,
          backgroundColor: "#fc5c65",
        },
      });
      

      【讨论】:

      • 更好的是,只需将resizeMode: "cover" 添加到背景样式中即可解决问题。
      猜你喜欢
      • 2020-12-15
      • 2018-08-22
      • 2012-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 2019-08-25
      • 1970-01-01
      相关资源
      最近更新 更多