【问题标题】:How to set 'hardwareBackPress' to another Stack如何将“hardwareBackPress”设置为另一个堆栈
【发布时间】:2020-02-13 06:58:57
【问题描述】:

//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”事件监听器以导航到另一个 StackNavigator。如果我像上面那样设置。此后压适用于所有页面。我只想为 TermsPage 设置这个监听器。并将此侦听器设置为导航到另一个 StackNavigator

【问题讨论】:

    标签: javascript react-native navigation react-native-android addeventlistener


    【解决方案1】:

    我用函数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
    

    【讨论】:

      【解决方案2】:

      你可以使用这个例子,这里我们在 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。 希望对您有所帮助,请随时提出疑问。

      【讨论】:

      • 我像你的代码那样做,但是当我在这个堆栈的另一个屏幕中单击返回按钮时,我再次回到我编写的那些堆栈。那是我的问题
      猜你喜欢
      • 2019-08-08
      • 2013-12-26
      • 2019-02-09
      • 1970-01-01
      • 2022-10-17
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多