简体   繁体   中英

How to conditionally change screenOptions for different react native screens in the same Navigator?

I have a Navigator with 2 screens. In one of them I want to show the headerRight component and in the other screen, I don't want to show the headerRight component.

My Navigation looks like this:

    <NavigationContainer>
      <Stack.Navigator screenOptions={{ 
        headerShown: true, 
        headerRight: () => <Switch /> // conitionally change this
      }}>
        <Stack.Screen name="Vocabulary" component={bottomNavigator} />
        <Stack.Screen name="Definition" component={Definition}  />
      </Stack.Navigator>
    </NavigationContainer>
  • Do I render headerRight conditionally based on what screen is visible?
  • Do I have multiple navigators?
  • Do I configure it within the rendered compnent (ie Definition )?

Try this way

componentDidMount() {
    this.props.navigation.setOptions({
      headerRight: <Switch />
    });
}

If you want to specify an option for a particular screen and not for all screens, then specify it in the option of the desired screen instead of in screenOptions :

<NavigationContainer>
  <Stack.Navigator
    screenOptions={{
      headerShown: true
    }}
  >
    <Stack.Screen
      name="Vocabulary"
      component={bottomNavigator}
      options={{
        // Show only for Vocabulary screen
        headerRight: () => <Switch />
      }}
    />
    <Stack.Screen name="Definition" component={Definition} />
  </Stack.Navigator>
</NavigationContainer>

If you don't want an option to apply to all screens in a navigator, don't specify it in screenOptions which is applies to all screens. Multiple navigators for it seem overkill.

More details https://reactnavigation.org/docs/screen-options

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM