【问题标题】:Is there a way to prevent the user pressing the back button on their device from popping the current view from the stack?有没有办法防止用户按下设备上的后退按钮从堆栈中弹出当前视图?
【发布时间】:2019-01-14 22:31:04
【问题描述】:

我正在使用来自 Wix(版本 2)的 React-Native-Navigation 在我的 React Native 应用程序中设置导航。我正在使用sideMenu 布局,中间部分是一个堆栈。当用户选择其中一个侧边菜单项时,所选视图被推送到该中心堆栈上。如果用户在 Android 上按下后退按钮,则视图将从堆栈中弹出,但我并不总是希望这种情况发生,主要是如果他们选择的视图是 WebView

如果视图是WebView,我想手动处理用户按下硬件后退按钮。如果WebView 可以“goBack”,则视图将返回,但如果不能,则视图将从堆栈中弹出(正常情况下)。

我尝试使用react-native 中的BackHandler 类覆盖后退按钮按下,这使我可以捕获该按下并让WebView 返回(如果可以),但是从堆栈也会着火。 React-Native-Navigation v2 中有没有办法告诉它,“嘿,我知道了,除非我告诉你,否则不要弹出。”?

我目前这部分的代码如下:

componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.backHandler);
}

componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.backHandler);
}

backHandler = () => {
    if (this.state.canGoBack) {
        this.webviewRef.current.goBack();

        // I thought this might force the back press to be
        // ignored by react-native-navigation, but no dice.
        return false; 
    } else {
        // WebView can't go back so pop view like normal
        Navigation.pop(this.props.componentId);
    }
}

我希望这只会在 WebView 当前无法返回时从堆栈中弹出视图,否则只会让 WebView 返回。

实际发生的是两个事件都触发了。 IE。 WebView 会返回,但视图也会从堆栈中弹出。

【问题讨论】:

    标签: react-native-navigation wix-react-native-navigation react-native-navigation-v2


    【解决方案1】:

    通过在 React Native Navigation 和 React Native 文档中进行更多挖掘,我能够找到这个问题的答案。

    事件订阅以相反的顺序调用(即最后注册的订阅在前),如果一个订阅返回 true,那么之前注册的订阅将不会被调用。

    所以问题出在我的backHandler 方法中。我需要返回true,而不是返回false

    backHandler = () => {
        if (this.state.canGoBack) {
            this.webviewRef.current.goBack();
    
            // We've handled the event so we return true and the
            // handler on the view's parent can effectively be ignored. Yay!
            return true;
        } else {
            // WebView can't go back so pop view like normal
            Navigation.pop(this.props.componentId);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多