React Native物理back返回键的使用
16lz
2022-04-19
直接使用通用代码就好了
componentWillMount() { if (Platform.OS === 'android') { BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid); } } componentWillUnmount() { if (Platform.OS === 'android') { BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid); } } onBackAndroid = () => { const navigator = this.refs.navigator;const { navigator } = this.props; const routers = navigator.getCurrentRoutes(); console.log('当前路由长度:'+routers.length); if (routers.length > 1) { navigator.pop(); return true;//接管默认行为 } return false;//默认行为 };
注意导入 Platform 和 BackAndroid 。
这里的 const { navigator } = this.props;
要看你具体的 navigator 是在哪里,这里是因为我的navigator 已经绑定了 ref="navigator"
,所以我直接改为 this.refs.navigator
就可以了。
需要注意的是,不论是bind还是箭头函数,
每次被执行都返回的是一个新的函数引用,
因此如果你还需要函数的引用去做一些别的事情(譬如卸载监听器),那么你必须自己保存这个引用
// 错误的做法
class PauseMenu extends React.Component{ componentWillMount(){ AppStateIOS.addEventListener('change', this.onAppPaused.bind(this)); } componentDidUnmount(){ AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this)); } onAppPaused(event){ }}
// 正确的做法1
class PauseMenu extends React.Component{ constructor(props){ super(props); this._onAppPaused = this.onAppPaused.bind(this); } componentWillMount(){ AppStateIOS.addEventListener('change', this._onAppPaused); } componentDidUnmount(){ AppStateIOS.removeEventListener('change', this._onAppPaused); } onAppPaused(event){ }}
// 正确的做法2
class PauseMenu extends React.Component{ componentWillMount(){ AppStateIOS.addEventListener('change', this.onAppPaused); } componentDidUnmount(){ AppStateIOS.removeEventListener('change', this.onAppPaused); } onAppPaused = (event) => { //把方法直接作为一个arrow function的属性来定义,初始化的时候就绑定好了this指针 }}
BackAndroid在iOS平台下是一个空实现,所以理论上不做这个Platform.OS === 'android'判断也是安全的。如果所有事件监听函数中,没有任何一个返回真值,就会默认调用默认行为特别注意:navigator是同一个,这个事件在最外层注册就行(不是initialRoute的组件,是AppRegistry的组件),否则会调用多次pop的,这个代码接管的是整个应用的后退键放到initialRoute里会有问题,你两三个页面测不出来,页面层次多了组件会unmount,然后事件就丢了addEventListener()第三个参数useCapture (Boolean)详细解析:
•true 的触发顺序总是在 false 之前;
•如果多个均为 true,则外层的触发先于内层;
•如果多个均为 false,则内层的触发先于外层。
更多相关文章
- Android(安卓)修改App中默认TextView的字体和颜色
- Android中使用SAX解析XML
- Android(安卓)LK Bootlaoder启动概览
- A20启动LUNCH选项修改
- Android(安卓)球碰撞反弹 (2)
- android 学习笔记有用代码片段(1)
- Android(安卓)设置字体大小和显示大小后界面混乱
- appium启动APP配置参数:
- 箭头函数的基础使用