項目中我們經常會遇到子組件和父組件垂直水平居中的問題,那么我們如何實現這個效果呢?
方法有很多種,下面以自定義按鈕為例簡述下實現方法,
A:主要使用這個來實現(相當於水平垂直居中):
justifyContent: 'center',
alignItems:'center',
首先要理解justifyContent、alignItems兩個布局屬性,詳情參考: React Native 布局 justifyContent、alignItems、alignSelf、alignContent
type FlexAlignType = "flex-start" | "flex-end" | "center" | "stretch" | "baseline"; justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around" | "space-evenly"; alignItems?: FlexAlignType;
效果如圖所示:
代碼如下:
<View style={style.btn_bg}>
<TouchableOpacity onPress={() => {
}}>
<View style={style.btn_blue}>
<Text style={style.btn}>測試一下下</Text>
</View>
</TouchableOpacity>
</View>
btn_bg: {
backgroundColor: 'yellow',
paddingHorizontal: 15,
paddingVertical: 8,
},
btn_blue: {
backgroundColor: '#3480FF',
height: 40,
borderRadius: 20,
justifyContent: 'center',
alignItems:'center',
},
btn: {
fontSize: DeviceHelp.fontSize(16),
color: '#FFFFFF',
backgroundColor: 'red'
},
B:當子控件是Text時也可以使用textAlign:'center'方式來實現(這種方式就是要求文本沒有背景色才可以達到上述效果,算是取巧),
父控件:justifyContent: 'center',
子控件:textAlign:'center'
效果如圖:

變動代碼:
btn_blue: { backgroundColor: '#3480FF', height: 40, borderRadius: 20, justifyContent: 'center', }, btn: { fontSize: DeviceHelp.fontSize(16), color: '#FFFFFF', backgroundColor: 'red', textAlign:'center' },
綜上所述:
最好的方案就是A,當子控件是Text時,可以考慮B方案。
