【问题标题】:Align the Header in center将页眉居中对齐
【发布时间】:2017-08-15 18:27:22
【问题描述】:

反应导航: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'
    }
});

【问题讨论】:

    标签: reactjs react-native react-navigation


    【解决方案1】:

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

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

    不足以使标题居中。
    您必须使用headerRight: (&lt;View&gt;&lt;/View&gt;) 才能出现在中心。

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

    【讨论】:

      【解决方案2】:

      titleStyle 属性已重命名为 headerTitleStyle 您现在可以通过 headerTitleStyle 将标题标题设置为样式,方法是将其传递给导航选项。

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

      【讨论】:

      • 谢谢。这解决了它,但有一个小问题。更新代码后,它与中心对齐,但不是中心。它更靠右。我认为这是向左箭头的原因,我该如何解决?我更新了我的问题中的屏幕截图。你能帮我解决这个问题吗?非常感谢。
      • @Somename 是的,这是由于返回按钮,您可以通过在导航选项中隐藏 headerLeft: null 来修复它。或在右侧放置另一个按钮。如果您不想在右侧放置按钮,可以将marginRight: 40 分配给headerTitleStyle
      • 我处理这个问题的方式(我也有一个headerLeft)是设置textAlign 并应用flex:5/6
      【解决方案3】:

      根据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

      【讨论】:

        猜你喜欢
        • 2011-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-08
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 2017-11-14
        相关资源
        最近更新 更多