美好的一天。
我尝试使用 reactnative 导航导航到另一个页面,但它在 reactnative 中显示"Undefined 不是一个对象(正在评估这个.props.navigation.navigate(">
这是我的代码
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>
);
}
}
我已经陷入困境了几个小时,我已经尝试了我在这个问题上看到的所有其他链接,但都无济于事。如果您能提供帮助,我将很高兴。谢谢。
你应该用 HOC withNavigation
包装你的组件,然后 prop 将在组件中可用,尝试这样的事情:
import { withNavigation } from 'react-navigation';
class TheStudent extends Component {
....
}
export withNavigation(TheStudent)
@Rachid Rhafour在他的回答中提到的一个解决方案。
您可以使用导航导出您的组件,该组件可以从反应导航导入。
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);