【问题标题】:Problem with custom header in react navigation反应导航中的自定义标题问题
【发布时间】:2021-08-28 13:19:27
【问题描述】:

我正在尝试使用反应导航制作自定义标题,但我无法获得正确的结果。我希望红色视图覆盖所有蓝色视图,但我无法弄清楚。

Here is a picture

我的 HomeStack.js:

const screens = {
  Home: {
    screen: HomeScreen,
  }
}

const options = {
  defaultNavigationOptions: {
    headerTitle: () => <Header/>,
    headerStyle: {
      backgroundColor: 'lightblue',
      height: 60,
      }
  }
}

const HomeStack = createStackNavigator(screens, options)

const Navigator = createAppContainer(HomeStack)

export default Navigator

我的 Header.js:

class Header extends Component {
  render() {
    return(
      <View style={style.conteiner}>
        <Text style={style.text}>Text</Text>
      </View>
    )
  }
}


const style = StyleSheet.create({
  conteiner: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'red',
  },
  text: {
    color: '#fff',
    fontSize: 20,
  }
})


export default Header

【问题讨论】:

  • 您是否尝试在conteiner 样式中添加flex: 1 属性?

标签: javascript react-native react-navigation


【解决方案1】:

如果我理解正确,那么您想为整个标题定义一个自定义组件。您正在使用自定义标头组件设置headerTitle:

const options = {
    defaultNavigationOptions: {
    headerTitle: () => <Header/>, <-- here
    headerStyle: {
    backgroundColor: 'lightblue',
    height: 60,
}

这就是文档中关于headerTitle 的内容:

有时您需要更多的控制,而不仅仅是更改文本和样式 您的标题 - 例如,您可能希望在适当位置呈现图像 的标题,或将标题变成一个按钮。在这些情况下,您可以 完全覆盖用于标题的组件并提供您的 拥有。

此选项仅用于替换标题组件,而不是整个标题。除非您有一些非常具体的要求,否则您可能会使用headerStyleheaderTintColorheaderTitle 的组合来实现您想要的。

【讨论】:

    【解决方案2】:

    您需要将自定义标头组件传递给堆栈导航器的 header 道具。

    headerTitle 用于标题组件内的标题。

    https://reactnavigation.org/docs/4.x/stack-navigator#header

    https://reactnavigation.org/docs/4.x/stack-navigator#headertitle

    https://reactnavigation.org/docs/4.x/stack-navigator

    【讨论】:

      猜你喜欢
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      相关资源
      最近更新 更多