undefined 不是一个对象(评估 _this2.props.navigation.navigate)

Jos*_*aza 1 javascript node.js reactjs react-native react-native-navigation

我正在使用react-native,但我遇到了导航器的问题。

代码:

应用程序.js

import React, {Component} from 'react';
import {
   AppRegistry,
   StyleSheet,
   Text,
   View,
} from 'react-native';

import { StackNavigator } from 'react-navigation';

import loginScreen from './src/components/loginView';
import registerScreen from './src/components/registerView';

const Appmemes = StackNavigator({
   Login: {screen: loginScreen},
   Register: {screen: registerScreen}
});

export default Appmemes;

AppRegistry.registerComponent('Appmemes', () => Appmemes);
Run Code Online (Sandbox Code Playgroud)

loginView.js 工作正常:

.
.
.
  <View style={styles.formContainer}>
          <LoginForm/>
  </View>
.
.
.    
Run Code Online (Sandbox Code Playgroud)

登录表单.js

import React, { Component } from 'react'
import { StyleSheet, TextInput, Text, View, TouchableOpacity, AppRegistry} from 'react-native'
import { StackNavigator} from 'react-navigation';

export default class LoginForm extends Component{
  render() {
      return(
      <View style={styles.container}>

          <TouchableOpacity style={styles.buttonContainer1}>
            <Text style={styles.buttonText}>Entrar</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.buttonContainer2} onPress={() => this.props.navigation.navigate('Login')}>

            <Text style={styles.buttonText}>Registrarse</Text>
          </TouchableOpacity>
      </View>
    );
  }
}

AppRegistry.registerComponent('LoginForm', () => LoginForm);

const styles = StyleSheet.create({...]);
});
Run Code Online (Sandbox Code Playgroud)

错误是:

undefined 不是一个对象(评估 _this2.props.navigation.navigate)

错误出现OnPress()在 LoginForm.js 中

onPress={() => this.props.navigation.navigate('Login')
Run Code Online (Sandbox Code Playgroud)

导致此错误的原因可能是什么?

Mus*_*Zia 5

简单地。<LoginForm navigation={this.props.navigation} />

发生错误的原因是LoginFrom没有使用直接加载,StackNavigator并且只有那些由 StackNavigator 直接加载的组件才能获得道具navigation(就像loginScreen您的情况一样)。内部的任何嵌套组件都loginScreen不会navigation自动接收 prop,因此我们需要将其显式传递给,LoginForm因为它将传递给loginScreen.

我在这里回答过类似的问题。

旁注:我相信您正在使用本身内部的原样从内部导航loginScreen到再次。因此,在这种情况下,您可能想要导航到. 所以你应该写.loginScreenthis.props.navigation.navigate('Login')LoginFormloginScreenRegisterthis.props.navigation.navigate('Register')

另外,您也不需要AppRegistry.registerComponent('LoginForm', () => LoginForm);这是因为您只需要向 注册一个根组件AppRegistry。因此,Appmemes应该只注册AppRegistry您已经注册的内容。LoginForm将自动由 进行安装loginScreen,而 又将由 进行安装Appmemes