使用Android...when,你在应用程序上向右滑动,它将卸载所有组件,并停止所有应用程序操作。第一个要卸载的组件似乎是父组件网(通常名为app.js),.please如果我在这一点上说错了,请纠正我。
当发生这种情况时,我知道componentWillUnmount事件会触发,因为我将下面的代码添加到了控制台中。
componentWillUnmount() {
console.log('app.js....componentWillUnmount');
}我的问题是,我是否可以在componentWillUnmount中添加一些额外的代码,这些代码可能会退出用户“你确定要退出应用程序吗?”....and给他们一个选择,所以说“不”,让应用程序继续运行。
发布于 2021-08-15 18:11:53
React-Native官方文档上的BackHandler API description提供了相同用例的示例。您可以在官方文档中查看给定的示例代码片段,并根据您的选择选择包含函数式组件或基于类的组件的示例。
您可以将该代码放在顶级组件中,如App.js或Routes.js。
自动隐藏吐司的另一种方法可以是:
使用功能组件
import React, {useEffect, useRef} from 'react';
import {Text, SafeAreaView, BackHandler, ToastAndroid} from 'react-native';
export default function App() {
const doubleBackToExitPressedOnce = useRef(false);
useEffect(() => {
const backAction = () => {
if (doubleBackToExitPressedOnce.current) {
BackHandler.exitApp();
return true;
}
ToastAndroid.show('Press back again to exit', ToastAndroid.SHORT);
doubleBackToExitPressedOnce.current = true;
setTimeout(() => {
doubleBackToExitPressedOnce.current = false;
}, 2000);
return true;
};
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
backAction,
);
return () => backHandler.remove();
}, []);
return (
<SafeAreaView>
<Text>Hello world!</Text>
</SafeAreaView>
);
}使用类组件:
import React, {Component} from 'react';
import {SafeAreaView, Text, BackHandler, ToastAndroid} from 'react-native';
export default class App extends Component {
backAction = () => {
if (this.doubleBackToExitPressedOnce) {
BackHandler.exitApp();
}
ToastAndroid.show('Press back again to exit', ToastAndroid.SHORT);
this.doubleBackToExitPressedOnce = true;
setTimeout(() => {
this.doubleBackToExitPressedOnce = false;
}, 2000);
return true;
};
componentDidMount() {
this.doubleBackToExitPressedOnce = false;
this.backHandler = BackHandler.addEventListener(
'hardwareBackPress',
this.backAction,
);
}
componentWillUnmount() {
this.backHandler.remove();
}
render() {
return (
<SafeAreaView>
<Text>Hello world!</Text>
</SafeAreaView>
);
}
}https://stackoverflow.com/questions/68788085
复制相似问题