How can we center title of react-navigation header

2019-04-22 21:14发布

React-navigation docs are still young, and reading through the issues is not working quite much for me (changes on each version) does anyone have a working method to center title in Android using react-navigation in React Native?

10条回答
Bombasti
2楼-- · 2019-04-22 21:28

Make sure to check the issues before resulting to stack overflow, normally more helpful.issue regarding your problem But as himanshu said in comments you need to access the title style property to adjust the title how you want.

static navigationOptions = {
    header: (navigation) => ({
      title: <Text style={{ 
            color: 'rgba(0, 0, 0, .9)', 
            fontWeight: Platform.OS === 'ios' ? '600' : '500',  
            fontSize: Platform.OS === 'ios' ? 17 : 18, 
            alignSelf: 'center' 
         }}>Filters</Text>,
      right: <SearchButton />,
      left: <CancelButton />,
    })
  };

As shown in the issue, i presume you've already managed to find a solution as this was a while ago. But for anyone else coming across this issue it may be helpful.

查看更多
ら.Afraid
3楼-- · 2019-04-22 21:29
headerTitleStyle: {
    color: 'white',
    textAlign: 'center',
               flex: 1
}
查看更多
姐就是有狂的资本
4楼-- · 2019-04-22 21:31

Use headerTitleStyle:

static navigationOptions = {
    headerTitleStyle: { alignSelf: 'center' },
    title: 'Center Title',
}

enter image description here

Modified 2019/03/12:

In year of 2018, after react-navigation v2 release (7 Apr 2018), for some reason alignSelf was not working anymore. Here it is the new working way, using headerLayoutPreset. from @HasanSH:

createStackNavigator({
   { ... // your screens},
   { ...,
     headerLayoutPreset: 'center' // default is 'left'
   })
查看更多
Anthone
5楼-- · 2019-04-22 21:35

The accepted answer only works for me if there isn't a back button present on the left-hand side. In that case, you need to set an empty View to the right-hand side to properly center it.

static navigationOptions = {
    headerTitleStyle: { alignSelf: 'center' },
    title: 'Center Title',
    headerRight: (<View />)
}
查看更多
迷人小祖宗
6楼-- · 2019-04-22 21:35

Set react-navigation header title in the center. Using the headerTitleStyle CSS.

static navigationOptions = {
        title: 'Home',
        headerTintColor: '#fff',
        headerTitleStyle: {
            width: '90%',
            textAlign: 'center',
        },
    };
查看更多
放荡不羁爱自由
7楼-- · 2019-04-22 21:40

The best way to do that is by implementing what is listed in the documentation: Inside the StackNavigatorConfig assign an optional property, as follows:

createStackNavigator({
   { ... // your screens},
   { ...,
     headerLayoutPreset: 'center' // default is 'left'
   })

headerLayoutPreset - Specifies how to lay out the header components.

By doing this you don't have to mess up with the styling at all. And it would be applied to all the nested screens in that stack.

Check the Source

查看更多
登录 后发表回答