How to set 'hardwareBackPress' to another Stack

浪尽此生 提交于 2020-04-30 11:47:24

问题


//TermsPage.tsx
const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({
    routeName: 'BottomTabNav',
    params:{showTerms:false}
  }),
  ],
});
componentWillUnmount() {
    BackHandler.addEventListener('hardwareBackPress',()=>{
      this.props.navigation.dispatch(resetAction)
      return true
    })
  }

How to set 'hardwareBackPress' eventListenner to navigate to another StackNavigator. If I set like above. This backpress work in all Pages. I want to set this listener only for TermsPage. And set this listener to navigate to another StackNavigator


回答1:


I solve this problem with function pop(). In the page, where I want to go another stack I added

const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({
    routeName: 'BottomTabNav',
    params:{showTerms:false}
  }),
  ],
});
handleBackButtonClick() {
    this.props.navigation.dispatch(resetAction);
    return true;
  }

And in another pages

handleBackButtonClick() {
    // @ts-ignore
    this.props.navigation.pop();
    return true;
  }
``` And voila



回答2:


you can use this example, here we bind this method in Constructer and also call this function whenever the screen is rendering back

 constructor(props) {
        super(props);
        this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
        this.state = {
        };

      }
      componentWillMount() {
        BackHandler.addEventListener(
          'hardwareBackPress',
          this.handleBackButtonClick,
        );
      }
      componentWillUnmount() {
        BackHandler.removeEventListener(
          'hardwareBackPress',
          this.handleBackButtonClick,
        );
      }
      handleBackButtonClick() {
        this.props.navigation.navigate('name of page where you want to nav');
        return true;
      }

From where you don't want to go back use this..

 componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }
 componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
  }
  handleBackButton() {
    return true;
  }

It will not let you go back from the page where you are, please import BackHandler from react-native. hope it helps, feel free for Doubts.



来源:https://stackoverflow.com/questions/60202096/how-to-set-hardwarebackpress-to-another-stack

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