簡體   English   中英

使用 React Native Alert 來確認/阻止后退按鈕導航

[英]Use a React Native Alert to confirm/block Back button navigation

我試圖在使用堆棧導航器的后退按鈕之前通過執行類似於此問題的操作來提示用戶進行確認,但結果我的結果似乎不同。

 const defaultGetStateForAction = SignedIn.router.getStateForAction; const asyncGetUserConfirmation = () => { return new Promise((resolve, reject) => { Alert.alert( "Discard changes?", "Your post will be lost if you confirm.", [ { text: "No, continue editing", onPress: () => { resolve(false); } }, { text: "Yes, discard changes", style: "cancel", onPress: () => { store.dispatch(setPost({})); resolve(true); } } ], { cancelable: false } ); }); }; SignedIn.router.getStateForAction = (action, state) => { if ( state && action.type === NavigationActions.BACK && Object.keys(store.getState().post).length ) { asyncGetUserConfirmation().then(continueAction => { console.log(continueAction); return continueAction ? defaultGetStateForAction(action, state) : null; }); } else { return defaultGetStateForAction(action, state); } };

當用戶觸摸后退按鈕時, SignedIn.router.getStateForActionif正常工作(如果帖子為空,則不詢問,否則彈出警報)。

我預計如果continueAction為真(在代碼段的末尾),用戶將被重定向回,但是在用戶與警報交互后,控制台上會顯示正確的結果,但無論continueAction是真還是假,用戶都是沒有導航回來。

其他一切都按預期工作,那么什么會讓return continueAction ? defaultGetStateForAction(action, state) : null; return continueAction ? defaultGetStateForAction(action, state) : null; 被“忽略”,甚至不拋出錯誤?

要在使用堆棧導航器的后退按鈕之前顯示確認,您可以覆蓋堆棧導航器的 onPress。

import React from "react";
import { View, Text, Alert } from "react-native";
import { HeaderBackButton } from "react-navigation";

export default class Detail extends React.Component {
  static navigationOptions = ({ navigation }) => {
    const handleClearPress = navigation.getParam("handleBackPress", () => {});
    return {
      title: "Details!",
      headerLeft: <HeaderBackButton onPress={handleClearPress} />
    };
  };

  componentDidMount() {
    // set handler method with setParams
    this.props.navigation.setParams({
      handleBackPress: this._handleBackPress.bind(this)
    });
  }

  _handleBackPress() {
    // Works on both iOS and Android
    Alert.alert(
      "Discard changes?",
      "Your post will be lost if you confirm.",
      [
        {
          text: "No, continue editing",
          onPress: () => console.log("No, continue editing")
        },
        {
          text: "Yes, discard changes",
          onPress: () => console.log("Yes, discard changes"),
          style: "cancel"
        }
      ],
      { cancelable: false }
    );
  }

  render() {
    return (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <Text>Detail Screen</Text>
      </View>
    );
  }
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM