我正在使用React Native开发我的移动的应用程序,我遇到了导航问题。我开始开发HomeScreen,FormatioScreen,AddPantScreen和SummaryScreen。我最近开发了一个身份验证页面,仅向管理员提供对所有页面的访问权限。另一方面,玩家应该只能访问FormationScreen。导航在HomeScreen和app.js上运行良好,但我不明白为什么它不能在我的AuthScreen上运行。你有什么建议吗?我是一个初学者开发者。
//AuthScreen.js
import React, { useState, useEffect, } from 'react';
import { View, Text, Button, TextInput, StyleSheet, TouchableOpacity } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useFocusEffect } from '@react-navigation/native';
import { NavigationContainer } from '@react-navigation/native';
export default function AuthScreen({ setIsAdmin }) {
const [password, setPassword] = useState('');
const [isAuthenticated, setIsAuthenticated] = useState(false);
const navigation = useNavigation();
console.log('Navigation in AuthScreen:', navigation);
const navigateToFormation = () => {
navigation.navigate('Formation');
};
const handleAdminLogin = () => {
if (password === 'test') {
setIsAdmin(true);
setIsAuthenticated(true);
} else {
alert('Mot de passe incorrect');
}
};
const handlePlayerLogin = () => {
setIsAdmin(false);
setIsAuthenticated(true);
console.log('After navigation to Formation');
};
useFocusEffect(
React.useCallback(() => {
if (isAuthenticated) {
console.log('Navigating to Formation');
// Déplacer la navigation à l'intérieur du useEffect
const navigateToFormation = () => {
navigation.navigate('Formation');
};
navigateToFormation();
}
}, [navigation, isAuthenticated])
);
return (
<View style={styles.container}>
<Text style={styles.title}>Page d'authentification</Text>
<TextInput
style={styles.input}
placeholder="Mot de passe"
secureTextEntry
onChangeText={(text) => setPassword(text)}
/>
<Button title="Se connecter en tant qu'admin" onPress={handleAdminLogin} />
<Button title="Se connecter en tant que joueur" onPress={handlePlayerLogin} />
<TouchableOpacity style={styles.button} onPress={navigateToFormation}>
<Text style={styles.buttonText}>🏐 JOUEURS 🏐</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 16,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginBottom: 16,
padding: 8,
width: '80%',
},
});
个字符
PS:我不需要应用程序的高级安全措施;它只是为了娱乐目的。没有敏感数据将存储在代码中。
非常感谢您的帮助??
我已经尝试了在这里和React Native嵌套导航文档中找到的许多东西,但都没有成功。我仍然是这个领域的初学者,尽管我研究了很多东西,但我已经在这上面停留了三天。😅
1条答案
按热度按时间zrfyljdw1#
不要手动导航到条件渲染屏幕。为不同的角色使用单独的屏幕集。下面是一个简单的示例:
字符串
请参阅Authentication flows了解更多信息。