【问题标题】:[[ERROR]] undefined is not an object(evaluating '_this2.props.navigation.push')[[ERROR]] undefined 不是一个对象(评估 '_this2.props.navigation.push')
【发布时间】:2018-05-31 01:19:21
【问题描述】:

伙计们,我遇到了这个问题,但我无法解决它,我尝试了很多东西,但这个错误对我来说很明显。所以我迷路了,请帮助我

this 在 main (Route) 中:App.js

const Router = createStackNavigator(
  {
    Login: {screen: LoginScreen},
    Julia: {screen: JuliaScreen},
  },
  {
    initialRouteName: 'Login',
    headerMode: 'none',
  }
)

LoginScreen.js --> 登录屏幕

          <View style = {styles.formContainer}>

              <LoginForm/>

          </View>

LoginForm.js --> 登录组件(登录表单)

import React, { Component } from 'react';
import {  View, Text, StyleSheet, TextInput, TouchableOpacity, StatusBar, AsyncStorage } from 'react-native';


import JuliaScreen from './JuliaScreen'

    export default class LoginForm extends Component {
      render() {
        return (

          <View style = {styles.container}>

            <StatusBar 
              barStyle = "light-content" 
            />

            <TextInput 

                onChangeText = {(username) => this.setState({username})}
                value = {this.state.username}
            />
            <TextInput 

                ref = {(input) => this.passwordInput = input}
                onChangeText = {(password) => this.setState({password})}
                value = {this.state.password}
            />

            <TouchableOpacity onPress = {  () => {this.props.navigation.push('Julia')} } style = {styles.btnContainer}>
                <Text style = {styles.btnText}>LOGIN</Text>
            </TouchableOpacity>    
          </View>
        );
      }

【问题讨论】:

标签: javascript reactjs react-native react-navigation


【解决方案1】:

根据您的Router 声明,LoginForm 不是navigator 的一部分,它不会引用navigation 对象。一种方法是在LoginScreen 组件中渲染LoginForm 时传递navigation 对象,例如

<LoginForm navigation={this.props.navigation}/>

但是这种方法不好。还有另一种更好的方法可以使navigation 对象可用于不属于navigator 的组件。函数是withNavigation。看看官方文档here

您只需将LoginForm 组件包装在withNavigation 中,就像

import { withNavigation } from 'react-navigation';
...
class LoginForm extends ... {
    ...
}
export default withNavigation(LoginForm);

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2019-02-04
    相关资源
    最近更新 更多