创建导航器时,未定义不是对象(评估 this.props.navigation.navigate)
2020-05-26
836
我试图在登录和注册之间进行简单的导航,但是我得到了“TypeError:undefined 不是评估‘_this2.props.navigation.navigate’的对象”。我不太明白为什么。
下面的代码:
SwitchNavigator.js
import React from 'react'
import { createSwitchNavigator, createAppContainer } from 'react-navigation';
import Login from '../screens/Login'
import Signup from '../screens/Signup'
import Profile from "../screens/Profile";
const SwitchNavigator = createSwitchNavigator(
{
Login: {
screen: Login
},
Signup: {
screen: Signup
},
Profile: {
screen: Profile
}
},
{
initialRouteName: 'Login'
}
)
export default createAppContainer(SwitchNavigator)
Login.js
import React from 'react'
import {View, Text, StyleSheet, TouchableOpacity, TextInput, Button} from 'react-native'
class Login extends React.Component {
state = {
email: '',
password: ''
}
render() {
return (
<View style={styles.container}>
<Text style={styles.jungleText}>Jungle</Text>
<TextInput
style={styles.inputBox}
value={this.state.email}
onChangeText={email => this.setState({ email })}
placeholder='Email'
autoCapitalize='none'
/>
<TextInput
style={styles.inputBox}
value={this.state.password}
onChangeText={password => this.setState({ password })}
placeholder='Password'
secureTextEntry={true}
/>
<TouchableOpacity style={styles.button}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<Button
title="Don't have an account yet? Sign up"
onPress={() => this.props.navigation.navigate('Signup')}
/>
</View>
)
}
}
export default Login
非常感谢你的帮助!
3个回答
尝试一下,将其粘贴到您的导航页面中,然后安装 -> npm install react-navigation-stack @react-native-community/masked-view
import React from "react";
import {
createSwitchNavigator,
createAppContainer,
createStackNavigator,
} from "react-navigation";
import Login from "../screens/Login";
import Signup from "../screens/Signup";
import Profile from "../screens/Profile";
const LoginStack = createStackNavigator({
Login: {
screen: Login,
},
});
const SignupStack = createStackNavigator({
Login: {
screen: Signup,
},
});
const ProfileStack = createStackNavigator({
Login: {
screen: Profile,
},
});
const SwitchNavigator = createSwitchNavigator(
{
Login: LoginStack,
Signup: SignupStack,
Profile: ProfileStack,
},
{
initialRouteName: "Login",
}
);
export default createAppContainer(SwitchNavigator);
mainak
2020-05-26
如果您是 Javascript 或 React Native 的新手,您会经常遇到此错误。当您尝试使用 '.' 对空对象访问内部对象/属性时,就会发生这种情况。在这种情况下,
this.props.navigation
为空,因此
this.props.navigation.navigate
将出现此错误。
一个简单的解决方案,像这样导出您的登录组件:
export default withNavigation(Login)
确保导入 withNavigation
import { withNavigation } from "react-navigation"
解释: withNavigation 只是一个高阶组件,可确保导航属性可用于您的登录组件。
Romit Kumar
2020-05-26
将您的类组件更改为函数组件。然后将导航作为参数传递给函数组件。然后使用 useState 钩子来处理您的状态。让我知道这是否有效
Inusah Said
2020-05-26