【问题标题】:Align close button on top right corner of ImageBackground react native对齐 ImageBackground 右上角的关闭按钮反应原生
【发布时间】:2022-01-03 17:56:14
【问题描述】:

如何在 react-native 中对齐 ImageBackground 组件右上角的关闭按钮图标

代码:

<ImageBackground 
  source={require('../images/AppIntro/1.png')} 
  style={{ width: '100%', height: 150 }} 
>
  <TouchableOpacity>
    <Icon name="md-close" style={styles.closeButton} />
  </TouchableOpacity>
</ImageBackground>

编辑:我正在尝试创建一个模式(弹出),它将在按钮单击时显示,因此绝对位置可能不起作用。

【问题讨论】:

标签: react-native


【解决方案1】:
<View>
    <Image
       source={require('../images/AppIntro/1.png')} 
       style={{ 
           width: '100%', 
           height: 150 
       }}/>
    <Icon 
       name="md-close" 
       style={{
           position: 'absolute',
           left: 0,
           right: 0,
           top: 0,
           bottom: 0
        }}/>
</View>

上面的代码将把你的图标放在图像的顶部,水平和垂直居中。您可以调整顶部、左侧、右侧和底部,并将其移动到图像顶部的任意位置。

【讨论】:

  • 实际上我正在尝试创建一个模态(弹出),因此 position: absolute 在我的情况下可能不起作用。虽然我认为我可以将关闭按钮对齐底部中心,这看起来也不错。
  • 我对此没有深入了解,但是关于定位的文档说值与下一个父元素有关,这意味着它取决于父视图,所以它是否会影响它模态与否?
  • 这里,你把Image和icon都包裹在View里面了,如果没有View就不行了,能告诉我outside view的意义吗?
  • 视图是两者的父视图。图标的位置:绝对值将与父视图的尺寸相关。因此,如果您没有提供父视图,则图标将位于顶级父视图的中心。在这里,View 将是 Image 的大小,然后 Icon 将绝对定位在 View 上,这实际上是在图像的尺寸上
【解决方案2】:
<View>
    <Image
        source={require('../images/AppIntro/1.png')} 
        style={{ width: '100%', height: 150 }}
    />
    <Icon name="md-close" 
          style={{
                position: 'absolute',
                right: 5,
                top: 5,
          }} />
</View>

这个工作的右上角..

【讨论】:

    【解决方案3】:

    您需要使用position: 'absolute' 将孩子与父母中任何您想要的地方对齐。在您的情况下,您需要使用topright 以及absolute position。考虑以下示例:

    <Parent>
      <Child style={{position: 'absolute', top: 5, right: 5}}>
        {...}
      </Child>
    </Parent>
    

    你可以阅读更多关于职位here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 2021-06-01
      相关资源
      最近更新 更多