項目中我們經常會遇到組件左右兩端展示的需求,實現的方法有很多種,
今天簡述下以下兩種方法:
A:子組件使用flex:1(自動填充)
優勢:
設置flex:1的組件會優先展示兄弟組件,然后自己才會填充父組件剩余部分。
假如設置左端組件flex:1,那么會優先展示右端組件,然后左端組件才會填充父組件剩余部分。
劣勢:
需要設置子組件
子組件:
設置flex:1的子組件會拉伸填充滿父組件剩余部分
適用場景:
全場景通用
一端優先展示,另一端動態變化的(文字過長且單行展示的)亦可正常展示
B:父組件使用justifyContent:'space-between'(兩端對齊)
優勢:
使用簡單,不需要操縱子組件
劣勢:
子組件優先級是一樣的,不能滿足一端優先顯示的場景
假如一端文本過長且一行展示時,另一端會被擠出父組件,導致顯示異常,
假如沒有限制行數,是不會出現展示問題的
子組件:
按實際內容展示不會拉伸填充父組件剩余部分
適用場景:
左右兩端有限顯示,
不涉及一端文本過長且要單行顯示的。
綜上所述:
兩種方法各有千秋,具體場景,具體使用,flex:1更具備通用性
下面是簡單的示例:
A:子組件使用flex:1
效果圖:
通過視圖結構層次,我們發現組件完全按照我們的意圖顯示。
視圖結構:
話不多說,直接上代碼:
左邊文本右端組件
<View style={style.item_top_bg}> <Text style={style.item_tab}>我是標題</Text> {/* 展開收起 */} <TouchableOpacity style={style.item_top_btn} onPress={() => { let open = this.state.openflag this.setState({ openflag: !open }) }}> <Text style={style.item_top_right_title}>{this.showTitle()}</Text> {this.showImg()} </TouchableOpacity> </View>
item_top_bg: { borderRadius: 8, marginHorizontal: 10, marginBottom: 10, paddingHorizontal: 15, paddingVertical: 20, flexDirection: 'row', alignItems: 'center', backgroundColor: '#FFFFFF', }, item_tab: { flex: 1, fontSize: DeviceHelp.fontSize(17), fontWeight: DeviceHelp.fontBold, color: '#3480FF', }, item_top_btn: { alignItems: 'center', flexDirection: 'row', },
左邊文本右邊文本
<View style={style.item_sub_bg}> {/* 左右 */} <View style={style.item_title_bg}> <Text style={style.item_left}>左</Text> <Text style={style.item_right}>右</Text> </View> {/* 分割線 */} <View style={style.item_line}></View> {/* 左右 */} <View style={style.item_title_bg}> <Text style={style.item_left}>我是左邊</Text> <Text style={style.item_right}>我是右邊</Text> </View> </View>
item_sub_bg: { borderRadius: 5, borderWidth: 1, borderColor: '#B8D2FF5C', backgroundColor: '#FCFDFF', paddingHorizontal: 15, paddingVertical: 17, }, item_title_bg: { alignItems: 'center', flexDirection: 'row', }, item_left: { fontSize: DeviceHelp.fontSize(14), color: '#666666', flex: 1, }, item_right: { fontSize: DeviceHelp.fontSize(14), color: '#333333', }, item_line: { marginVertical: 17, height: 0.5, backgroundColor: '#EBEBEB', },
B:父組件使用justifyContent:'space-between'
結構圖:
代碼變動如下:
兩者都是子組件注釋// flex:1,父組件增加justifyContent:'space-between',
左邊文本右邊組件:
item_top_bg: { borderRadius: 8, marginHorizontal: 10, marginBottom: 10, paddingHorizontal: 15, paddingVertical: 20, flexDirection: 'row', alignItems: 'center', backgroundColor: '#FFFFFF', justifyContent:'space-between', }, item_tab: { // flex:1, fontSize: DeviceHelp.fontSize(17), fontWeight: DeviceHelp.fontBold, color: '#3480FF', },
左邊文本右邊文本
item_title_bg: { alignItems: 'center', flexDirection: 'row', justifyContent:'space-between', }, item_left: { // flex:1, fontSize: DeviceHelp.fontSize(14), color: '#666666', },