React Native中Switch Navigator失效问题求助
问题分析与解决方案
你遇到的两个问题(默认显示LoginScreen、按钮点击无响应)都是因为按钮的onPress事件绑定写法错误导致的,下面具体拆解并修复:
1. 核心问题:onPress的写法误区
你当前的写法是:
onPress={this.props.navigation.navigate('Login')}
这种写法会在组件渲染阶段就立即执行navigate方法,而不是等待用户点击按钮时才触发。这直接导致:
- 组件一加载就自动跳转到LoginScreen,所以你看到默认显示Login而非Loading
- 按钮点击时已经没有可执行的回调逻辑,所以点击毫无反应
2. 修复代码
需要把onPress改成箭头函数包裹的形式,确保只有用户点击时才触发导航操作:
修复LoadingScreen的跳转按钮
<Button title="Move to LoginScreen" onPress={() => this.props.navigation.navigate('Login')} />
修复LoginScreen的跳转按钮
<Button title='Sign in' onPress={() => this.props.navigation.navigate('Loading')} />
3. 完整修复后的代码
import React from 'react' import { StyleSheet, Platform, Image, Text, View, TextInput, Button, ActivityIndicator } from 'react-native' import { createAppContainer, createSwitchNavigator } from 'react-navigation' import { createBottomTabNavigator } from 'react-navigation-tabs'; import Ionicons from 'react-native-vector-icons/Ionicons'; class LoadingScreen extends React.Component { render() { return ( <View style={styles.loadingcontainer}> <Text>Loading</Text> <ActivityIndicator size="large" /> {/* 修复此处的onPress绑定 */} <Button title="Move to LoginScreen" onPress={() => this.props.navigation.navigate('Login')} /> </View> ) } } class LoginScreen extends React.Component { state = { email: '', password: '' } render() { return ( <View style={styles.logincontainer}> {/* 修复此处的onPress绑定 */} <Button title='Sign in' onPress={() => this.props.navigation.navigate('Loading')} /> <Button title='Sign Up' /> </View> ) } } const styles = StyleSheet.create({ loadingcontainer: { flex: 1, justifyContent: 'center', alignItems: 'center', }, logincontainer: { flex: 1, justifyContent: 'center', alignItems: 'center' }, logintextInput: { height: 40, width: '90%', borderColor: 'gray', borderWidth: 1, marginTop: 8 }, }) const App = createSwitchNavigator( { Loading: { screen: LoadingScreen, }, Login: { screen: LoginScreen, }, }, // 可选:显式设置初始路由,确保默认显示LoadingScreen(修复后已生效,加上更稳妥) { initialRouteName: 'Loading' } ); export default createAppContainer(App);
额外优化建议
建议在createSwitchNavigator的配置里加上initialRouteName: 'Loading',显式指定初始页面,避免后续路由顺序调整时出现默认页面异常,让代码逻辑更清晰。
内容的提问来源于stack exchange,提问作者John99
相关产品推荐
相关产品推荐

