首页 > 解决方案 > Undefined 不是 reactnative 中的对象(评估 this.props.navigation.navigate)

问题描述

再会。

我尝试使用 reactnative 导航导航到另一个页面,但它显示“Undefined is not an object (Evaluating this.props.navigation.navigate) in reactnative”

这是我的代码

import React, { Component } from 'react';
import {Text, View, Image, Alert} from 'react-native';
import { Icon, Button, List, ListItem, Left, Thumbnail, Body, Right } from 'native-base'; 
import {styles} from '../../../css/Designs';
import OptionsMenu from "react-native-options-menu";
const myIcon = (<Icon name='more' style={{fontSize:30,color:'#000'}}/>);

export class TheStudent extends Component {

    constructor(props) {
    super(props);
};

editItem = (student) => {
    this.props.navigation.navigate('AllStudents');
}

deleteItem = (student) => {
    Alert.alert(
        '',
        'Delete student?',
        [
            {
                text: 'No',
                onPress: () => console.log('Cancel Pressed'),
                style: 'cancel',
            },

            { 
                text: 'Yes', 
                onPress: () => this.deleteTheItem(student)
            },
        ],
        {cancelable: false},
      );
}

deleteTheItem = (student) => {
    alert(student);
}

render() {

    return(

        <List>
            <ListItem avatar>
                <Left>
                    <Thumbnail source={require('../../../img/male_avatar.png')} />
                </Left>
                <Body>
                    <Text style={styles.userName}>{this.props.surname} {this.props.firstname} {this.props.middlename} </Text>
                    <Text>{this.props.matric}    {this.props.level}L   {this.props.phone}</Text>
                </Body>
                <Right>
                    <OptionsMenu
                        customButton={myIcon}
                        options={["Edit", "Delete"]}
                        actions={[this.editItem.bind(this,this.props.id), this.deleteItem.bind(this,this.props.id)]}/>
                </Right>
            </ListItem> 
        </List>
    );
}
}

我已经被困了几个小时,我已经尝试了我在这个问题上看到的所有其他链接,但都无济于事。如果您能提供帮助,我将很高兴。谢谢。

标签: react-native

解决方案


这是@Rachid Rhafour 在他的回答中提到的一种解决方案。

您可以使用导航导出组件,该组件可以从 react-navigation 导入。

import { withNavigation } from 'react-navigation';

class YourClassName extends Component {

}
export withNavigation(YourClassName)

另一种方法是您可以制作路由文件,通过该文件您可以轻松导航到任何组件文件。

例如:如果有两个或三个组件要导航或从导航,您应该通过路由文件维护该路由。

import React from "react";
import { createStackNavigator, createAppContainer } from "react-navigation";
import ScreenOne from "./ScreenOne";
import ScreenTwo from "./ScreenTwo";
const AppNavigator = createStackNavigator({
  Home: {
    screen: ScreenOne
  },
  Profile: {
    screen: ScreenTwo
  }
});

export default createAppContainer(AppNavigator);

推荐阅读