将页眉居中对齐

Align the Header in center

反应导航:1.0.0-beta.11

反应:16.0.0-alpha.12

本机反应:0.47.1

我正在按照 ReactNavigation 教程将 Header 从传递的道具渲染到屏幕。

class ChatScreen extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    title: `Chat with ${navigation.state.params.user}`,   // <- Talking bout this
  });
  render() {
    const { params } = this.props.navigation.state;
    return (
      <View>
        <Text>Chat with {params.user}</Text>
      </View>
    );
  }
}

我希望 title: Chat with ${navigation.state.params.user} 中的 title 出现在中间。我该如何设计它?我也想换个颜色。

我试过这个suggestion但是没用。

非常感谢。

更新代码后,它对齐到中心但不是完全中心。它更靠右。我认为这是左边箭头的原因,我该如何解决?

更新代码:

static navigationOptions = ({ navigation }) => ({
    title: `${navigation.state.params.name.item.name}`,
    headerTitleStyle: {
    color: '#000',
    textAlign: 'center',
    alignSelf: 'center'
    }
});

titleStyle 属性 已重命名为 headerTitleStyle 您现在可以通过 headerTitleStyle 将您的 header 标题样式传递给导航选项。

....
headerTitleStyle: {
      color: 'color value',
      textAlign: 'center',
      alignSelf: 'center' //if style using flexbox
}
....

如果您的屏幕有 headerLeft后退按钮,

headerTitleStyle: {
  textAlign: "center",
  alignSelf: "center"
}

不足以成为中心标题。
您必须使用 headerRight: (<View></View>) 才能出现在中心。

 static navigationOptions = {
    headerTitleStyle: {
      textAlign: "center",
      alignSelf: "center"
    }
    headerRight: <View><View />
  };

根据React Navigation 5.x

您必须使用 headerTitleAlign 使标题居中。在android中它的值默认是left,在iOS中它的值是center.

<Stack.Navigator
  initialRouteName='Welcome'
  screenOptions={{
    headerTitleStyle: {
      color: 'white',
      fontSize: 20,
    },
    headerTitleAlign: 'center',
  }}
>
  <Stack.Screen name='Welcome' component={Welcome}/>
</Stack.Navigator>

更多详情:https://reactnavigation.org/docs/stack-navigator/#headertitlealign