gpt4 book ai didi

javascript - 如何使用 React Native 阻止特定屏幕的硬件后退按钮?

转载 作者:行者123 更新时间:2023-12-05 05:45:11 26 4
gpt4 key购买 nike

我用React Native做的应用,打开的画面如下。用户在注册屏幕上注册。我想防止它使用手机后退按钮在 A 屏幕上倒退。如果我以第一种方式执行此操作(您可以在下面为页面 B 编写的代码中看到它),我会得到我想要的,并且它只会在按下 A 屏幕上的后退按钮时发出警告。但这样一来,当用户在C屏注销时,切换到Launch屏时同样给出警告。我不明白这是怎么发生的。如果我采用第二种方式,当我在所有屏幕上按下后退按钮时,它会发出此警告。拜托,我只想让它只在从 A 屏幕按下后退按钮时发出警告。我该怎么做?

启动屏幕 --> 注册屏幕 --> A 屏幕 --> B 屏幕 --> C 屏幕

启动

import React, { useEffect } from "react"
import { View } from "react-native"
import { useSelector } from "react-redux"
import { loginSelector } from "../../redux/LoginRedux"


const Launch = ({ navigation }) => {

const isLoggedIn = useSelector(loginSelector)

useEffect(() => {
if (!isLoggedIn) {
navigation.navigate("SignUp")
} else {
navigation.navigate("D-Screen")
}
}, [])

return (
<View/>
)
}

export default Launch

B屏

// First way (It only works on the b screen, but when the user logs out, it gives this warning when the Launch screen is opened.)

useEffect(() =>
navigation.addListener('beforeRemove', (e) => {
e.preventDefault();
Alert.alert(
"Warning,
"Do you want to exit",
[
{ text: "No", onPress: () => null },
{ text: "Yes", onPress: () => BackHandler.exitApp() }
],
{ cancelable: true }
);
}), [])


/* Second way (it works on all screens not just b screen)*/

useEffect(() => {
const backAction = () => {
Alert.alert("Hold on!", "Are you sure you want to go back?", [
{
text: "Cancel",
onPress: () => null,
style: "cancel"
},
{ text: "YES", onPress: () => BackHandler.exitApp() }
]);
return true;
};

const backHandler = BackHandler.addEventListener(
"hardwareBackPress",
backAction
);

return () => backHandler.remove();
}, []);

D 画面

//

const logOut = () => {
dispatch(setLoginStatus(false));
navigation.reset({
index: 0,
routes: [{ name: 'Launch' }]
})
};

//

导航

const Stack = createStackNavigator();

const StackNavigator = () => {
return (
<Stack.Navigator
initialRouteName={"Launch"}
screenOptions={{headerShown: false, animationEnabled: false}}>
<Stack.Screen name={Launch} component={"Launch"} />
<Stack.Screen name={SignUp} component={"SignUp"} />
<Stack.Screen name={AScreen} component={"A"} />
<Stack.Screen name={BScreen} component={"B"} />
</Stack.Navigator>
);
};

最佳答案

我认为它可以工作:您可以使用 navigation.isFocused() 检查用户是否在 A 屏幕中

const backAction = () => {
if (navigation.isFocused()) {
Alert.alert("Hold on!", "Are you sure you want to go back?", [
{
text: "Cancel",
onPress: () => null,
style: "cancel"
},
{ text: "YES", onPress: () => BackHandler.exitApp() }
]);
return true;
}
};

const backHandler = BackHandler.addEventListener(
"hardwareBackPress",
backAction
);

关于javascript - 如何使用 React Native 阻止特定屏幕的硬件后退按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71429227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com