相对于另一个 zIndex 更高的视图(React Native),你如何垂直和水平居中一个视图?

How do you vertically and horizontally center a View with respect to another View that is at a higher zIndex (React Native)?

Image of what I am envisioning

我正在尝试向滑块添加中心刻度线。

是否可以将视图 1 相对于视图 2 垂直和水平居中,同时在视图 1 上方渲染视图 2(使用 zIndex)?我可以通过在 Y 方向上将视图 1 放置在视图 2 下方并设置视图 1 的边距使其显示在视图 2 下方(在 Z 方向)来实现此目的。这是执行此操作的正确方法吗?

通过摆弄边距来实现这一点似乎可能会在不同尺寸的屏幕上引起问题。

您可以像这样用父 View 包围 View

<View style={{ width: '100%', justifyContent: 'center', alignItem: 'center' }}>
  //horizontal
  <View style={{ zIndex: 1, elevation: 1, width: '100%', height: '20'% }}></View>
  //vertical
  <View style={{ zIndex: 0, elevation: 0, height: '100%', width: '20%' }}></View>
</View>

这将根据屏幕尺寸动态调整,因为所有高度和宽度值都是使用百分比设置的。

尝试给 view1 和 view2 绝对位置,并将它们放置在垂直和水平居中的父容器中。这将允许它们重叠而不必使用边距,并且自然地将 view2 放在 view1 的顶部而无需使用 zIndex

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.specialContainer}>
        <View style={styles.tall}/>
        <View style={styles.long}/>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  specialContainer:{
     width:300,
     aspectRatio:1,
     backgroundColor:'pink',
     alignItems:'center',
     justifyContent:'center'
  },
  long:{
    position:'absolute',
    backgroundColor:'purple',
    width:'60%',
    height:24,
    // alignSelf:'center'
  },
  tall:{
    position:'absolute',
     backgroundColor:'green',
    height:'60%',
    width:24,
    // alignSelf:'center',
  }
});

试试看here