如何使用ImageBackground为react-native中的屏幕设置背景图像.

Waq*_*qas 27 react-native

当我在react-native中使用时,它会发出警告,即不允许与子项一起使用,并且将来会出错.用户改为.

所以,如果我使用它不会给出我正在使用的预期结果

这是我写的使用的代码

<ImageBackground source={require('../../img/splash/splash_bg.png')} style={styles.backgroundImage} >
        </ImageBackground>
Run Code Online (Sandbox Code Playgroud)

风格代码是

const styles = StyleSheet.create({
backgroundImage: {
    flex: 1,
    // width: undefined,
    // height: undefined,
    // flexDirection: 'column',
    // backgroundColor:'transparent',
    // justifyContent: 'flex-start',


},}
Run Code Online (Sandbox Code Playgroud)

预期结果:使用<Image>时获取 结果使用<ImageBackground>

任何帮助将非常感激.谢谢

Tia*_*vêa 51

现在RN有"ImageBackground"组件.

<ImageBackground
  source={yourSourceFile}
  style={{width: '100%', height: '100%'}}
> 
    <....yourContent...>
</ImageBackground>
Run Code Online (Sandbox Code Playgroud)

  • 我不知道它是否很奇怪,但如果我没有指定'width'和'height'属性,它只会给我一个错误,而且我没有在任何地方看到这个.你的回答让我发现了什么是错的:D (7认同)

BLD*_*LDD 10

我通过以下方式实现了

import { ImageBackground ] from 'react-native';

<ImageBackground style={ styles.imgBackground } 
                 resizeMode='cover' 
                 source={require('./Your/Path.png')}>

   //place your now nested component JSX code here

</ImageBackground>
Run Code Online (Sandbox Code Playgroud)

然后是样式:

imgBackground: {
        width: '100%',
        height: '100%',
        flex: 1 
},
Run Code Online (Sandbox Code Playgroud)

  • 从 'react-native' 导入 { ImageBackground ]; 应该将 ] 更改为 } 对吧? (2认同)

Ale*_*nov 5

两种选择:

  1. 尝试将宽度和高度设置为设备屏幕的宽度和高度
  2. 老位置绝对好

#2 的代码:

 render(){
    return(
        <View style={{ flex: 1 }}>
           <Image style={{ width: screenWidth, height: screenHeight, position: 'absolute', top: 0, left: 0 }}/>
           <Text>Hey look, image background</Text>
        </View>
    )
}
Run Code Online (Sandbox Code Playgroud)

编辑:对于选项#2,你可以尝试一下resizeMode="stretch|cover"

编辑 2:请记住,选项 #2 渲染图像,然后按此顺序渲染之后的所有内容,这意味着某些像素会渲染两次,这可能会对性能产生非常小的影响(通常不明显),但仅供您参考