简体   繁体   中英

react-native: back button handler

I want to detect value is changed when hardware back button pressed.

but, using BackHandler in useEffect, it is not working.

here is my code...

 useEffect(() => { BackHandler.addEventListener("hardwareBackPress", backAction); return () => { BackHandler.removeEventListener("hardwareBackPress", backAction) } },[]); const backAction = () => { BackActionAlert( navigation, addedImage.length > 0 || deletedImage.length > 0, 'ModifyDetail' ); return true; }; const BackActionAlert = (navigation, requireBackAlert, fromWhere) => { if (requireBackAlert) { Alert.alert( "warning", alertMessage(fromWhere), [ { text: 'NO', style: 'cancel', }, { text: 'OK', onPress: () => navigation.goBack() } ], { cancelable: true, } ); } else { navigation.goBack(); } };

in my code, Array addedImage and deletedImage have no element when that component mounted,

so, it return false (I guess)

How can i fix it?

Create a folder called hooks where your App.js is located

Inside hooks folder, create a file called useBackHandler.js

Inside useBackHandler.js paste this

import { useEffect } from "react";
import { BackHandler } from "react-native";

export function useBackHandler(handler) {
  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", handler);

    return () => BackHandler.removeEventListener("hardwareBackPress", handler);
  }, [handler]);
}

Then use it like this wherever you want to handle backpress

import useBackHandler from "../hooks/useBackHandler";
// Make sure the import is correct


useBackHandler(() => {
  if (want_to_do_something) {
    // Do Something
    return true;
  }
  return false;
});

So in your case it will be used like this

useBackHandler(() => {
  if (addedImage.length > 0 || deletedImage.length > 0) {
    BackActionAlert(navigation, 'ModifyDetail');
    return true;
  }
  return false;
});

const BackActionAlert = (navigation, fromWhere) => {
  Alert.alert(
    'warning',
    alertMessage(fromWhere),
    [
      {
        text: 'NO',
        style: 'cancel',
      },
      {
        text: 'OK',
        onPress: () => navigation.goBack(),
      },
    ],
    {
      cancelable: true,
    }
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM