简体   繁体   English

React Native-如何在背景图像上显示内容并将内容垂直居中

[英]React Native - How to display content over background Image and Vertically center that content

This same question is previously asked by many people. 以前很多人都问过这个问题。 The issue is that Image component cannot contain children .If you want to render content on top of an image, consider using the <ImageBackground> component or absolute positioning. 问题是Image组件不能包含子代 。如果要在图像顶部渲染内容,请考虑使用<ImageBackground>组件或绝对定位。

I have referred the article Text Over Image and previous question on stack overflow . 我已经提到了“ 文本在图像上”一以及关于堆栈溢出的先前问题。 Content over image is working using <ImageBackground> component. 使用<ImageBackground>组件可以处理图像上的内容。 But how to make it work using <Image> component instead? 但是如何使用<Image>组件使其工作呢?

Part 1 (Text / Body of your question) 第1部分(问题的正文/正文)

To answer the text/body of your question, the official docs say: 为了回答您的问题的文字/正文, 官方文档说:

A common feature request from developers familiar with the web is background-image. 来自熟悉网络的开发人员的常见功能请求是背景图片。 To handle this use case, you can use the <ImageBackground> component, which has the same props as , and add whatever children to it you would like to layer on top of it. 要处理此用例,可以使用<ImageBackground>组件,该组件具有与相同的道具,并向其中添加任何您想在其上分层的子级。

Thus, <ImageBackground> component is specifically designed for ability to display content over a background image. 因此, <ImageBackground>组件经过专门设计,可以在背景图像上显示内容。 So, you must use <ImageBackground> component for placing content over an image. 因此, 必须使用<ImageBackground>组件将内容放置在图像上。 This behavior cannot be achieved through <Image> component. 通过<Image>组件无法实现此行为。

Part 2 (Title of your question) 第2部分(您的问题的标题)

Now, to answer the TITLE of your question, try this: 现在,要回答您的问题的标题,请尝试以下操作:

<ImageBackground
  style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}
  source={require('path/to/img')}>
     <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', width: '100%' }}>
         <Text>Centered Text (both vertically and horizontally)</Text>
     </View>
</ImageBackground>

justifyContent works along primary axis (in this case column /vertical). justifyContent沿主轴(在本例中为column /垂直)工作。 alignItems works along secondary axis (in this case row /horizontal). alignItems沿辅助轴(在本例中为row /水平)工作。

You may not need width: '100%' in child View, but I think that I've experienced some issues a couple of times. 您可能不需要width: '100%'在子视图中为width: '100%' ,但是我认为我已经遇到过几次问题。 So you can experiment with that. 因此,您可以尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM