react-native 布局示例

react-native中样式的控制比Web上的简化了很多,但是也会有所不同,所以需要试一试属性的使用才能使用更简洁的方法实现同样的效果。

1.单纯的Text和View元素都是在垂直上是包裹元素,水平上100%伸展。

<View style={styles.container}>
  <Text>hah</Text>
</View>

或者

<Text  style={styles.container}>hah</Text>

const styles = StyleSheet.create({
  container: {
  marginTop: 50,
  backgroundColor: '#747474'
  }
});

  

 

2. Text的布局属性 textAlign enum('auto', 'left', 'right', 'center', 'justify')

可以控制Text中的文本在Text中的水平对齐方式

那么当给Text设置height时,如何控制文本在Text中的垂直居中?
属性 textAlignVertical enum('auto', 'top', 'bottom', 'center')  只在android上有效

第一种方法:设置lineHeight,如果是在Web中,如果设置Text的height为100,再设lineHeight为100,文本就应该居中了,但是在native中,发现不是,

这里设置的lineHeight 是文本的底部距离Text顶部的距离,比如Text高度是100,fontSize是20,那么应该设置lineHeight为60 才能使文本垂直居中。

第二种方法:给Text元素设置padding,也是需要计算,比如Text高度是100,fontSize是20,那么应该设置paddingTop为40 才能使文本垂直居中。

总之,单Text元素使文本垂直居中的方法,没有一个直接的属性能够办到,需要根据Tex的height和fontSize做计算。那个要不想计算只能通过外层嵌套View。

给Text直接设置flexbox的alignItems 和justifyContent也是无效的。

native 当中所有的元素都类似block,

但是当父元素设置了alignItems:'center' 时,子元素水平方向也进行了包裹,不会占据100%,但是也不会水平排列,

但是当父元素设置了flexDirection:'row' 时,子元素就都变成了类似inline-block,水平包裹并且水平排列。水平排列默认不会换行,即使超出屏幕宽度,

要想折行可以设置 flexWrap :'wrap' 来设置折行。

还发现,当设置flexDirection:'row' 后,alignItems:'center' 也就失效了,当我们设置了flexDirection:'row' ,也就说明我们要水平布局了,所以水平居中也就没有什么意义了。 

alignSelf enum('auto', 'flex-start', 'flex-end', 'center', 'stretch') 

给元素设置alignSelf属性,可以相对于父元素进行自我定位,实现在父元素内可以有多种align

<View style={styles.container}>
<Text style={{backgroundColor:'red',alignSelf:'center'}}>alignSelf</Text>
<Text style={{backgroundColor:'red',alignSelf:'flex-end'}}>flex-end</Text>
</View>

水平布局方面:

flex通过设定数字来按比例划分宽度,

当需要进行固定宽度与自适应宽度的需求时,在Web上时,一般固定宽度的会用float或者absolute,然后自适应部分用margin。

在native当中,不需要设置,自适应的部分会自动占用固定宽度以外的空间。

<View style={styles.container}>
<Text style={{width:50,backgroundColor:'red'}}>50</Text>
<Text style={{flex:1, backgroundColor:'blue'}}>flex:1</Text>
<Text style={{width:50,backgroundColor:'red'}}>50</Text>
<Text style={{flex:1, backgroundColor:'blue'}}>flex:1</Text>
</View>

即使元素设置了position:'absolute',flex的元素仍然和它处于同一个文档流中

<View style={styles.container}>
<Text style={{width:50,backgroundColor:'red'}}>50</Text>
<Text style={{flex:1, backgroundColor:'blue'}}>flex:1</Text>
<Text style={{width:50,backgroundColor:'red',position:'absolute',right:0,top:0}}>50</Text>
</View>

 

posted @ 2016-03-30 11:01  杨博客  阅读(4223)  评论(0编辑  收藏  举报