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 84020a0b27
commit 5ae0badc44
2 changed files with 36 additions and 29 deletions

View File

@@ -115,12 +115,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,
@@ -171,22 +165,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

@@ -123,18 +123,45 @@ function DrawerViewBase({
React.useEffect(() => {
let subscription: NativeEventSubscription | undefined;
if (drawerStatus === 'open') {
// 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 (drawerStatus === 'open') {
// 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();
return () => {
subscription?.remove();
if (Platform.OS === 'web') {
document?.body?.removeEventListener?.('keyup', handleEscape);
}
};
}, [handleDrawerClose, drawerStatus, navigation, state.key]);
const renderDrawerContent = ({ progress }: any) => {