fix: only handle back button in drawer when focused

This commit is contained in:
Satyajit Sahoo
2021-04-02 05:21:18 +02:00
parent 4b8155386b
commit cceaa6780d
2 changed files with 37 additions and 30 deletions

View File

@@ -116,12 +116,6 @@ export default class DrawerView extends React.Component<Props> {
statusBarAnimation: 'slide',
};
componentDidMount() {
if (Platform.OS === 'web') {
document?.body?.addEventListener?.('keyup', this.handleEscape);
}
}
componentDidUpdate(prevProps: Props) {
const {
open,
@@ -172,22 +166,8 @@ export default class DrawerView extends React.Component<Props> {
componentWillUnmount() {
this.toggleStatusBar(false);
this.handleEndInteraction();
if (Platform.OS === 'web') {
document?.body?.removeEventListener?.('keyup', this.handleEscape);
}
}
private handleEscape = (e: KeyboardEvent) => {
const { open, onClose } = this.props;
if (e.key === 'Escape') {
if (open) {
onClose();
}
}
};
private handleEndInteraction = () => {
if (this.interactionHandle !== undefined) {
InteractionManager.clearInteractionHandle(this.interactionHandle);

View File

@@ -122,19 +122,46 @@ export default function DrawerView({
React.useEffect(() => {
let subscription: NativeEventSubscription | undefined;
if (isDrawerOpen) {
// We only add the subscription when drawer opens
// This way we can make sure that the subscription is added as late as possible
// This will make sure that our handler will run first when back button is pressed
subscription = BackHandler.addEventListener('hardwareBackPress', () => {
handleDrawerClose();
const handleClose = () => {
// We shouldn't handle the back button if the parent screen isn't focused
// This will avoid the drawer overriding event listeners from a focused screen
if (!navigation.isFocused()) {
return false;
}
return true;
});
handleDrawerClose();
return true;
};
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
handleClose();
}
};
if (isDrawerOpen) {
// We only add the listeners when drawer opens
// This way we can make sure that the listener is added as late as possible
// This will make sure that our handler will run first when back button is pressed
subscription = BackHandler.addEventListener(
'hardwareBackPress',
handleClose
);
if (Platform.OS === 'web') {
document?.body?.addEventListener?.('keyup', handleEscape);
}
}
return () => subscription?.remove();
}, [handleDrawerClose, isDrawerOpen, navigation, state.key]);
return () => {
subscription?.remove();
if (Platform.OS === 'web') {
document?.body?.removeEventListener?.('keyup', handleEscape);
}
};
}, [handleDrawerClose, isDrawerOpen, navigation]);
const focusedRouteKey = state.routes[state.index].key;