我正在尝试使用监听器实现 Backhandler,在 componentWillMount 中添加监听器,在 componentWillUnMount 中删除监听器,但是当我们推送到其他组件时不会调用 componentWillUnMount。那么其他组件中也有Listener,react-native-router-flux与tabbar是否存在问题
最佳答案
为了使返回处理程序能够使用集中式配置,我通常会将处理程序放在名为 AppNavigation
的组件中,该组件是 Router 组件的父组件。
它看起来像:
<AppNavigation>
<Router>
<Scene key="root">
{/* other scenes */}
</Scene>
</Router>
</AppNavigation>
处理 AppNavigation 中的后退按钮将相对简单:
import React, {Component} from "react";
import {BackAndroid} from "react-native";
import {Actions} from "react-native-router-flux";
class AppNavigation extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
//listens to hardwareBackPress
BackAndroid.addEventListener('hardwareBackPress', () => {
try {
Actions.pop();
return true;
}
catch (err) {
console.debug("Can't pop. Exiting the app...");
return false;
}
});
}
componentWillUnmount(){
console.log("Unmounting app, removing listeners");
BackAndroid.removeEventListener('hardwareBackPress');
}
render() {
return this.props.children;
}
}
export default AppNavigation;
附注不过,不要忘记区分 Android 和 iOS,因为我相信 iOS 没有后退按钮。
关于react-native - 如何在react-native-router-flux中使用带有标签栏的BackHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44516317/