我正在使用react-native,但我遇到了导航器的问题。
代码:
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 工作正常:
.
.
.
<View style={styles.formContainer}>
<LoginForm/>
</View>
.
.
.
登录表单.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({...]);
});
错误是:
undefined is not an object (evaluating _this2.props.navigation.navigate)
错误出现在 LoginForm.js 的 OnPress()
onPress={() => this.props.navigation.navigate('Login')
导致此错误的原因是什么?
最佳答案
简单地说。 <LoginForm navigation={this.props.navigation} />
发生错误的原因是 LoginFrom
未使用 StackNavigator
直接加载并且只有那些由 StackNavigator 直接加载的组件才会获得 navigation
prop(就像你的例子中的 loginScreen
)。 loginScreen
内的任何嵌套组件不会收到navigation
prop 自动,因此我们需要将其显式传递给 LoginForm
因为它会被传递到 loginScreen.
我回答过类似的问题here .
旁注:我相信您正在从内部导航 loginScreen
至loginScreen
再次使用 this.props.navigation.navigate('Login')
如LoginForm
在里面loginScreen
本身。因此,在这种情况下,您可能想要导航到 Register
。所以你应该写this.props.navigation.navigate('Register')
.
另外,您也不需要 AppRegistry.registerComponent('LoginForm', () => LoginForm);
这是因为你只需要注册一个根组件 AppRegistry
。所以,Appmemes
只能用 AppRegistry
注册你已经在做了。 LoginForm
将自动由 loginScreen
挂载依次由 Appmemes
安装.
关于javascript - undefined 不是一个对象(评估 _this2.props.navigation.navigate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46202911/