反应原生背景图像

时间:2017-11-20 21:18:08

标签: react-native login background-image

我需要帮助。我想在下面的背景图片上添加内容 这是我的代码:

<View style={{flex:1}}>
                <Image
                style={styles.mainContainer}
                source={require('../images/samples/login_bg.png')}>
                <LoginForm/>
                </Image>
            </View>

它向我显示了这个错误:

Error: The  component cannot contain children. If you want to render content on top of the image, consider using absolute positioning.

2 个答案:

答案 0 :(得分:2)

来自React Native官方文档:

  

熟悉网络的开发人员的常见功能请求是   背景图片。要处理此用例,您可以使用    组件,具有相同的道具,和   添加你想要在它上面分层的任何孩子。

     

你可能不想在某些情况下使用,因为   实施很简单。参考来源   代码以获得更多洞察力,并在何时创建自己的自定义组件   需要的。

return (
  <ImageBackground source={...}>
    <Text>Inside</Text>
  </ImageBackground>
);

你可以尝试

<View style={{flex:1}}>
    <ImageBackground
    style={styles.mainContainer}
    source={require('../images/samples/login_bg.png')}>
       <LoginForm/>
    </ImageBackground>
</View>

答案 1 :(得分:0)

如您所述,您可以将图片定位为绝对,以便在容器中展开所有其他项目。通过这样做,您的所有其他组件仍将遵循所有flex定位样式,并且图像将仅在后台。注意:您必须首先定义图像,如

  

组件按定义的顺序呈现。

这就是id做的方式,就像这样

<View style={{flex:1}}>
    <Image
       style={styles.mainContainer}
       source={require('../images/samples/login_bg.png')}>
    </Image>
    <LoginForm/>
</View>

和样式(注意:这会将图像放在父视图的左上角)

mainContainer: {
    position: 'absolute'
    left: 0,
    top: 0
}

然后您可以使用图片尺寸,例如将width设置为Dimensions.get("window").width将水平填充屏幕。我相信你必须处理图像的延伸,所以看看here

相关问题