在我的场景中,我试图为android后退按钮处理程序创建全局类,并在多个屏幕类文件中重用它。怎么做?我尝试了下面的代码,但我不知道如何从其他类访问普通类。
我的下面的代码(Androidhandler.tsx)
export default class hardware extends Component {
constructor(props) {
super(props);
this.BackButton = this.BackButton.bind(this);
}
componentWillMount() {
BackHandler.addEventListener'BackPress',this.BackButton);
}
componentWillUnmount() {
BackHandler.removeEventListener('BackPress',this.BackButton);
}
BackButton() {
if(this.props.navigation){
this.props.navigation.goBack(null);
return true;
}
}
}
答案 0 :(得分:0)
以下代码允许您在要使用android后退按钮返回时显示警报,您需要按如下方式使用react native BackHandler 组件。
import { BackHandler } from "react-native"
export default class hardware extends Component {
constructor(props) {
super(props);
this.BackButton = this.BackButton.bind(this);
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.BackButton);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', () => {
if (this.props.navigator && this.props.navigator.getCurrentRoutes().length > 1) {
this.navigator.pop();
return true;
}
return false;
});
}
BackButton() {
Alert.alert(
'Warning',
'Are you sure to leave?',
[
{
text: 'Cancel',
style: 'cancel'
},
{ text: 'OK', onPress: () => BackHandler.exitApp() }
],
);
return true;
}
}