1

I'm working with react-native and I'm facing a problem with navigators.

The code:

App.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);

loginView.js works correctly:

.
.
.
  <View style={styles.formContainer}>
          <LoginForm/>
  </View>
.
.
.    

LoginForm.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({...]);
});

The error is:

undefined is not an object (evaluating _this2.props.navigation.navigate)

The error is in OnPress() in LoginForm.js

onPress={() => this.props.navigation.navigate('Login')

What could be the cause for this error?

4

1 回答 1

4

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

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

我在这里回答了一个类似的问题。

旁注:我相信您正在从内部导航loginScreenloginScreen再次使用this.props.navigation.navigate('Login')as LoginFormis insideloginScreen本身。因此,在这种情况下,您可能的意思是导航到Register. 所以你应该写this.props.navigation.navigate('Register')

另外,你也不需要AppRegistry.registerComponent('LoginForm', () => LoginForm);这是因为你只需要注册一个根组件AppRegistry。所以,Appmemes应该只注册AppRegistry你已经在做的事情。LoginForm将自动被挂载,loginScreenAppmemes.

于 2017-09-14T05:11:40.390 回答