反应本机绝对定位

时间:2020-07-08 14:28:22

标签: css react-native layout css-position absolute

render() {
    return (
      <View style={{position: 'absolute'}}>
        <View style={{top: 50, width:50, height: 50, backgroundColor:'green'}} ></View>
        <View style={{top: 50, width:50, height: 50, backgroundColor:'blue'}} ></View>
        <View style={{top: 50, width:50, height: 50, backgroundColor:'purple'}} ></View>
      </View>
    );
  }

由于我使用的是绝对定位,因此我希望将三个正方形放置在彼此相同的位置。但是我得到的是这样:

enter image description here

我可以在没有任何自动布局的情况下将三个正方形精确定位在我要求的位置吗?

3 个答案:

答案 0 :(得分:1)

是的,您必须使每个位置都绝对定位。

<View>
    <View style={{position: 'absolute', top: 50, width:50, height: 50, backgroundColor:'green'}} ></View>
    <View style={{position: 'absolute', top: 50, width:50, height: 50, backgroundColor:'blue'}} ></View>
    <View style={{position: 'absolute', top: 50, width:50, height: 50, backgroundColor:'purple'}} ></View>
</View>

答案 1 :(得分:1)

您做错了,您需要对每个正方形应用position:absolute

尝试一下:

<View>
    <View style={{top: 50, width:50, height: 50, position: 'absolute',backgroundColor:'green'}} ></View>
    <View style={{top: 50, width:50, height: 50,position: 'absolute', backgroundColor:'blue'}} ></View>
    <View style={{top: 50, width:50, height: 50, position: 'absolute',backgroundColor:'purple'}} ></View>
  </View>

答案 2 :(得分:0)

问题是您的父视图位置绝对正确,但是每个孩子都会在内部中自动布局。您应该对要定位的每个元素应用绝对定位。

class Test extends StatefulWidget {
  
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
    final a = A.of(context);
    return Container();
  }
}