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

标签 javascript reactjs react-native

之前很多人都问过同样的问题。问题是 图像组件不能包含子组件。如果您想在图像之上渲染内容,请考虑使用 <ImageBackground>组件或绝对定位。

我已经引用了文章Text Over Image和上一个关于 stack overflow 的问题。图像上的内容正在使用 <ImageBackground> 工作成分。但如何使用 <Image> 使其工作组件代替?

最佳答案

第 1 部分(问题的正文/正文)

要回答您问题的正文/正文,official docs说:

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>组件专门设计用于在背景图像上显示内容的能力。因此,您必须使用<ImageBackground>用于将内容放置在图像上的组件。此行为无法通过 <Image> 实现组件。

第 2 部分(问题标题)

现在,要回答您问题的标题,请尝试以下操作:

<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沿主轴工作(在本例中 column/垂直)。 alignItems沿辅助轴工作(在本例中 row/水平)。

您可能不需要width: '100%'在 child View 中,但我认为我已经遇到过一些问题几次。所以你可以尝试一下。

关于javascript - React Native - 如何在背景图像上显示内容并垂直居中该内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49443035/

相关文章:

javascript - jQuery 如果.hasClass,则启用.hover

reactjs - 如何修复React中的 'TypeError: Cannot read property '映射'未定义'

reactjs - 自动关闭 ='outside' 不适用于 react-bootstrap 中的多个菜单

react-native - 无法使用 React Native 调试器进行调试

javascript - Chrome 丰富通知仅适用于扩展程序?

javascript - Google Analytics 转换代码无效

javascript - Dimple Barplot 无法使用分组或排序规则有效地对齐或排序条形图

node.js - 无法在 Node js 上安装 firebase 模块 : error 404

javascript - React Native 卡片图像封面

javascript - 在 react-native 中将嵌套 Realm 对象转换为 json