Just an Update for edition 6.x as see in RN docs
function ScreenWithCustomBackBehavior() {
// ...
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
if (isSelectionModeEnabled()) {
disableSelectionMode();
return true;
} else {
return false;
}
};
BackHandler.addEventListener( hardwareBackPress , onBackPress);
return () =>
BackHandler.removeEventListener( hardwareBackPress , onBackPress);
}, [isSelectionModeEnabled, disableSelectionMode])
);
// ...
}
Alternatively as a hook
import {useNavigation} from @react-navigation/native ;
import {useEffect, useState, useCallback} from react ;
export const usePreventGoBack = () => {
const navigation = useNavigation();
const [allow, setAllow] = useState(false);
const beforeRemoveListener = useCallback(
e => {
if (allow) {
return;
}
e.preventDefault();
},
[allow],
);
useEffect(() => {
const unsub = navigation.addListener( beforeRemove , beforeRemoveListener);
return () => {
unsub();
};
}, [navigation, beforeRemoveListener, allow]);
return (cb: () => void) => {
setAllow(true);
setTimeout(() => {
cb();
});
};
};
绕行
const continuePressed = () => {
allowBackButton(() => {
navigation.popToTop();
});
};