如何将 'hardwareBackPress' 设置为另一个 Stack

How to set 'hardwareBackPress' to another Stack

//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
    })
  }

如何设置 'hardwareBackPress' eventListenner 以导航到另一个 StackNavigator。如果我像上面那样设置。此 backpress 在所有页面中都有效。我只想为 TermsPage 设置此侦听器。并将此侦听器设置为导航到另一个 StackNavigator

你可以使用这个例子,这里我们在Constructer中绑定这个方法,并且在屏幕渲染回来的时候调用这个函数

 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;
      }

从你不想返回的地方使用这个..

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

它不会让你从你所在的页面返回,请从react-native导入BackHandler。 希望对你有帮助,有疑问欢迎留言

我用函数 pop() 解决了这个问题。 在页面中,我想转到另一个堆栈,我添加了

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

在另一页中

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