react-native的定位样式

2,005 阅读2分钟
前言

对于一个经常游走于 web 端的前端开发来说,我们都知道 cssposition 属性,position: 'absolute' 的元素,永远是相对与最近一个设置了position: relative 或者 position: 'absolute' 的父层级元素。然而在 react native 中却不是这样😅(曾经我还傻傻的以为是一样的😿)

现在就让我来好好的探索一番,在RN中,position 是如何定义和使用的。

特意去看看了 react-native 中对定位的定义,让我豁然开朗。

Absolute & Relative Layout

  • relative (default value) By default, an element is positioned relatively. This means an element is positioned according to the normal flow of the layout, and then offset relative to that position based on the values of toprightbottom, and left. The offset does not affect the position of any sibling or parent elements.
  • absolute When positioned absolutely, an element doesn't take part in the normal layout flow. It is instead laid out independent of its siblings. The position is determined based on the toprightbottom, and left values.

在实际的开发中,需要记住的就是:

绝对定位

元素的绝对定位是相对于父元素的

    <View style={styles.container}>
      <View style={styles.C1}>
        <View style={styles.p1}><Text>p1</Text></View>
        <View style={styles.p2}><Text>p2</Text></View>
      </View>
      <View style={styles.C2}><Text>C2</Text></View>
      <Text style={styles.p3}>p3相对父元素</Text>
      <View style={styles.p4}><Text>p4相对兄弟元素</Text></View>
    </View>
    
    p3: {
    backgroundColor: '#7951BD',
    padding: 10,
    position: 'absolute',
    bottom: -20,
    left: 20
  },
    

注意下图中 p3元素 的位置

react native

相对定位

元素的相对定位是相对于它的上一个非绝对定位的兄弟元素的原始位置,就是 top=0,left=0 的位置

注意上图中 p4 元素的位置

  • 附完整的测试代码:
  const Test = () => {

  return(
    <View style={styles.container}>
      <View style={styles.C1}>
        <View style={styles.p1}><Text>p1</Text></View>
        <View style={styles.p2}><Text>p2</Text></View>
      </View>
      <View style={styles.C2}><Text>C2</Text></View>
      <Text style={styles.p3}>p3相对父元素</Text>
      <View style={styles.p4}><Text>p4相对兄弟元素</Text></View>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    height: 300,
    width: 300,
    backgroundColor: '#eee',
  },
  
  C1: {
  },
  p1: {
    width: 40,
    height: 40,
    backgroundColor: '#5051BD',
    position: 'absolute',
    right: 0,
    bottom: 0,
    zIndex: 10
  },
  p2: {
    width: 40,
    height: 40,
    backgroundColor: '#1000DB',
  },

  C2: {
    height: 80,
    width: '100%',
    backgroundColor: '#eea',
    left: 30,
    top: 20
  },
  p3: {
    backgroundColor: '#7951BD',
    padding: 10,
    position: 'absolute',
    bottom: -20,
    left: 20
  },
  p4: {
    backgroundColor: '#9951BD',
    // position: 'absolute',
    padding: 10,
    bottom: 0,
    left: 0
  }
})

文章所涉及的知识点是自己在日常开发中的感悟.

如有不当之处,望指正🤝🤝🤝!让我们一起进步吧