【发布时间】:2019-07-22 09:07:10
【问题描述】:
首先,对不起我的英语。
我正在尝试使用 React Navigation 和 BackHandler 处理硬件 android 后退按钮。但是,我不能真正使用 goBack() 反应导航功能。
所以,我得到了一个类 androidBackButton.js:
import {BackHandler, Alert} from 'react-native';
const handleAndroidBackButton = callback => {
BackHandler.addEventListener('hardwareBackPress', () => {
callback();
return true;
});
};
const removeAndroidBackButtonHandler = () => {
BackHandler.removeEventListener('hardwareBackPress', () => {});
}
const exitAlert = () => {
Alert.alert(
"Quitter l'application",
"Êtes vous sûr de vouloir quitter l'application ?",
[
{text: 'Non', style: 'cancel'},
{text: 'Oui', onPress: () => BackHandler.exitApp()},
]
);
};
export {handleAndroidBackButton, removeAndroidBackButtonHandler, exitAlert};
要使用它,我在这样的屏幕中使用 componentDidMount 和 componentWillUnmount :
componentDidMount() {
handleAndroidBackButton(this.props.navigation.goBack());
}
componentWillUnmount() {
removeAndroidBackButtonHandler();
}
但是.. 就像你肯定知道的那样,我不能在 componentDidMount 中调用道具,因为我会收到一个警告,即“无法对未安装的组件执行 React State 更新。”。即使仅在我按下 android 硬件后退按钮时调用该操作,它也会在我加载组件时尝试定义它。所以,这行不通。
顺便说一句,我试着这样定义它:
componentDidMount() { handleAndroidBackButton(() => {this.props.navigation.goBack()}); }
通过这种方式,不会显示任何警告。但是当我点击硬件按钮时,什么都没有发生..
所以是的,有人知道发生了什么?有没有办法在不产生任何错误的情况下实现这一点?
非常感谢!
【问题讨论】:
标签: react-native react-navigation