2017-11-18 102 views
1

我試圖模仿堆棧導航標題象下面這樣: enter image description here如何在同一行中存在其他組件時水平居中組件?

在標題完全集中而有左側同一行中返回按鈕。

我試圖用justifyContent: 'space-between'在右側有一個空的View,但標題會偏離右側一點。我應該如何處理這個問題?

renderHeader功能:

_renderHeader =() => { 
    return (
     <View style={styles.headerAbsolute}> 
     <View style={styles.bar}> 
      <ButtonBack 
      text={"Resumes"} 
      onPress={() => this._onNavBackHandler()} 
      /> 
      {true ? (
      <Text style={styles.headingFixed}>{this.state.title}</Text> 
     ) : (null)} 
      <View/> 
     </View> 
     </View> 
    ) 
    } 

這些都是風格:

bar: { 
    height: 55, 
    flexDirection: "row", 
    alignItems: 'flex-end', 
    justifyContent: 'space-between', 
    paddingHorizontal: 10, 
    paddingBottom: 5, 
    }, 
    headingFixed: { 
    fontSize: TITLE_TERTIARY, 
    fontWeight: 'bold', 
    color: COLOR_DARK_SECONDARY, 
    backgroundColor: 'transparent', 
    }, 

回答

1

我會在這裏使用Flex。 請注意,我在下面的示例中僅使用了borderWidth以供參考,以顯示它的外觀。

我會flexDirection行和我會給一個flex: 1所有的意見裏

App.js

import React, { Component } from 'react'; 
import { 
    View, 
    Text 
} 
from 'react-native'; 

class App extends Component{ 
    render(){ 
    return(
     <View> 
     <View style={styles.navBar}> 
      <View style={styles.itemStyle}> 
      <Text style={{fontSize: 18, color: 'blue'}}>Resumes</Text> 
      </View> 
      <View style={styles.itemStyle}> 
      <Text style={{fontSize: 20, color: 'blue'}}>Settings</Text> 
      </View> 
      <View style={styles.itemStyle}></View> 
     </View> 

     </View> 
    ) 
    } 
} 

const styles = { 
    navBar: { 
    marginTop: 42, 
    height: 36, 
    flexDirection: 'row', 
    alignItems: 'center' 
    }, 
    itemStyle: { 
    flex: 1, 
    height: 36, 
    alignItems: 'center', 
    justifyContent: 'center', 
    borderWidth: 1 
    } 
} 

export default App; 

您可以在這裏面的觀點玩耍。移動其中一個子視圖內的buttonBack。

Comp

1

我能想到的兩種方法可以做到這一點,但也顯得相當理想。

第一種方式是使用一個透明元件具有固定的寬度和justifyContent: 'space-between',因爲你表示:

<View style={{flexDirection: 'row', justifyContent: 'space-between'}}> 
    <Text style={{width: 80}}>left</Text> 
    <Text>center</Text> 
    <Text style={{width: 80, color: 'transparent'}}>right</Text> 
</View> 

設置一個固定的寬度,在每個側上的元件將導致中間元件水平居中。

另一種方法是使用絕對造型。使用leftright的百分比需要React Native> = 0.42。

<View> 
    <Text>Left</Text> 
    <Text style={{position: 'absolute', width: 50, left: '50%', marginLeft: -25}}>Center</Text> 
</View>