Modifying back button with react-navigation on specific screen

和自甴很熟 提交于 2019-12-12 10:50:03

问题


I'm using react-navigation as my navigation lib, and I wonder how can I change the 'back' button (that is added automatically by react-navigation) functionality for a specific screen?

I mean instead of going one step in the stack of screens I want it to go 2 steps back in stack. or do it manually by giving it a screen name (again only on one component).

thanks.


回答1:


You can override back button for a specific screen with navigationOptions of that screen. You can read more info about overriding back button in react-navigation docs

Example from docs

class HomeScreen extends React.Component {
  static navigationOptions = {
    headerTitle: <LogoTitle />,
    headerRight: (
      <Button
        onPress={() => alert('This is a button!')}
        title="Info"
        color="#fff"
      />
    ),
  };
}

Overriding the back button

The back button will be rendered automatically in a StackNavigator whenever it is possible for the user to go back from their current screen — in other words, the back button will be rendered whenever there is more than one screen in the stack.

Generally, this is what you want. But it's possible that in some circumstances that you want to customize the back button more than you can through the options mentioned above, in which case you can specify a headerLeft, just as we did with headerRight, and completely override the back button.




回答2:


Consider, that you have 3 screens A, B, C respectively. So, the default functionality of the back button in StackNavigator is:- If you press the Back Button on screen C, it will take you to the previous screen i.e, screen B. To override that you could do something like this on screen C:-

import { HeaderBackButton } from 'react-navigation';
static navigationOptions = ({navigation}) => {
  return{
    headerLeft:(<HeaderBackButton onPress={()=>{navigation.navigate('A')}}/>)
 }
}



回答3:


You can do this while creating the stack navigator as well. Updated as of react-navigation v4.

import { createStackNavigator, HeaderBackButton } from "react-navigation-stack";

const yourStackNavigator = createStackNavigator({
  SomeRoute: SomeScreen,
  SpecificRoute: {
    screen: SpecificScreen,
    navigationOptions: ({ navigation }) => {
      return {
        headerLeft: (<HeaderBackButton onPress={_ => navigation.navigate("Somewhere")}/>)
      }
    }
  },
});


来源:https://stackoverflow.com/questions/49477330/modifying-back-button-with-react-navigation-on-specific-screen

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