反应导航中自定义 header 的问题

Problem with custom header in react navigation

我正在尝试使用 React 导航制作自定义 header,但我无法获得正确的结果。我想让红色视图覆盖所有蓝色视图,但我无法弄清楚。

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

如果我没理解错的话,那么你想为整个header定义一个自定义组件。您正在使用自定义 header 组件来设置 headerTitle:

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

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

Sometimes you need more control than just changing the text and styles of your title -- for example, you may want to render an image in place of the title, or make the title into a button. In these cases you can completely override the component used for the title and provide your own.

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

的组合来实现您正在寻找的东西

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

headerTitle 用于 header 组件内的标题。

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