Specify a custom DrawerNavigator header

大憨熊 提交于 2020-01-05 21:35:39

问题


I am using a DrawerNavigator and a StackNavigator

const AppDrawer = DrawerNavigator(
  {
    Inbox: {
      path: '/',
      screen: WelcomeContainer,
    },
    Drafts: {
      path: '/sent',
      screen: SettingsContainer,
    },
  },
  {
    initialRouteName: 'Inbox',
    contentOptions: {
      activeTintColor: '#e91e63',
    },
  }
);


const AppNavigator = StackNavigator({
  Home: {
    screen: AppDrawer,
    navigationOptions: ({navigation}) => ({
      header: false
    })
  },
  Settings: {
  screen: SettingsContainer,
  navigationOptions: ({navigation}) => ({
    title: navigation.state.params.title
  })
},
  About: {
  screen: About,
  navigationOptions: ({navigation}) => ({
    title: navigation.state.params.title
  })
}
})

For each element clicked on the drawer I want to show always the same header. I am using a custom header from react-native-elements. I implement it in the WelcomeContainer component with this code

render() {
<Header
  leftComponent={<MyCustomLeftComponent />}
  centerComponent={<MyCustomCenterComponent />} 
  rightComponent={<MyCustomRightComponent />}
/>
}

Shall I re-write this code in every component I want to it have the header or is it possible to indicate the header in DrawerNavigator, and if yes how?


回答1:


I had the same problem and did the following:

const AppDrawer = DrawerNavigator(
  {
    Inbox: {
      path: '/',
      screen: WelcomeContainer,
    },
    Drafts: {
      path: '/sent',
      screen: SettingsContainer,
    },
  },
  {
    navigationOptions: { header: null }, // <--- add this
    initialRouteName: 'Inbox',
    contentOptions: {
      activeTintColor: '#e91e63',
    },
  }
);

// simple HOC
const withHeader = (WrappedComponent) => { 
  return class WithHeader extends React.Component {
    render() {
      return (
        <View style={{ flex: 1 }}>
          <Header
            leftComponent={<MyCustomLeftComponent />}
            centerComponent={<MyCustomCenterComponent />}
            rightComponent={<MyCustomRightComponent />}
          />
          <WrappedComponent {...this.props} />
        </View>
      )
    }
  }
}

const AppNavigator = StackNavigator({
  Home: {
    screen: withHeader(AppDrawer), // <------ wrap the drawer
    navigationOptions: ({ navigation }) => ({
      header: false
    })
  },
  Settings: {
    screen: SettingsContainer,
    navigationOptions: ({ navigation }) => ({
      title: navigation.state.params.title
    })
  },
  About: {
    screen: About,
    navigationOptions: ({ navigation }) => ({
      title: navigation.state.params.title
    })
  }
})


来源:https://stackoverflow.com/questions/46807505/specify-a-custom-drawernavigator-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!