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>