React Native Android 独有组件之 BackH
2019-03-22 本文已影响0人
Kevin_小飞象
监听设备上的后退按钮事件。
方法
-
static exitApp()
-
static addEventListener(eventName, handler)
-
static removeEventListener(eventName, handler)
实例
1. 需求:实现 app 双击退出。
2. 逻辑代码
import React, {Component} from 'react';
import {
StyleSheet,
View,
Alert,
ToastAndroid,
Button,
BackHandler,
DatePickerAndroid
} from 'react-native';
var firstClick = 0;
export default class App extends Component {
constructor(props) {
super(props);
this.handleBack = this.handleBack.bind(this);
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBack);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBack);
}
handleBack = () => {
var times = (new Date()).valueOf();
if (times - firstClick > 2000) {
firstClick = times;
ToastAndroid.show('再按一次退出', ToastAndroid.SHORT);
return true;
} else {
return false;
}
}
render() {
return (
<View style={styles.container}>
<Button
title='日期对话框'
onPress={() => {
DatePickerAndroid.open()
.then(({ action, year, month,day }) => {
if (action !== TimePickerAndroid.dismissedAction) {
Alert.alert(year + '/' + month+'/'+day);
}
})
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
})
3. 效果图