[英]react-native: undefined is not an object (evaluating '_this2.props.navigation') with react navigation
I just started developing in react native and i'm experiencing an error, i've included Drawer navigation in my app and when its tapped in the content view, the side menu bar opens up but when its tapped on there我刚刚开始在 React Native 中进行开发,但遇到了错误,我在我的应用程序中包含了抽屉导航,当它在内容视图中被点击时,侧边菜单栏会打开,但是当它被点击时
<TouchableOpacity onPress={() =>this.props.navigation.toggleDrawer()}
style={{padding:10}}>
<Icon size={27} name='ios-menu' color='#fff' />
</TouchableOpacity>
it throws an error.它抛出一个错误。
undefined is not an object (evaluating '_this2.props.navigation')
below is my script下面是我的脚本
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button, TouchableOpacity} from 'react-native';
import {Container,
Header,
Content,
List,
ListItem,
Left,
Icon,
Body,
Title,
Right} from 'native-base';
class HomeScreen extends Component{
static navigationOptions = {
title: 'Home',
headerStyle: {
backgroundColor: '#28608c',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
headerLeft:(
<TouchableOpacity onPress={() =>this.props.navigation.toggleDrawer()}
style={{padding:10}}>
<Icon size={27} name='ios-menu' color='#fff' />
</TouchableOpacity>
),
headerRight:(
<TouchableOpacity style={{padding:10}}>
<Icon size={27} name='search' color='#fff' />
</TouchableOpacity>
)
};
render() {
return (
<Container>
<Content contentContainerStyle={{
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}}>
<Text onPress={() =>this.props.navigation.toggleDrawer()}>HomeScreen</Text>
</Content>
</Container>
);
}
}
export default HomeScreen;
From the react-navigation documentation :从反应导航文档:
It might be tempting to try to use
this.props
inside ofnavigationOptions
, but because it is a static property of the component,this
does not refer to an instance of the component and therefore no props are available.尝试在
navigationOptions
使用this.props
可能很诱人,但由于它是组件的静态属性,因此this
不引用组件的实例,因此没有可用的道具。 Instead, if we makenavigationOptions
a function then React Navigation will call it with an object containing{ navigation, navigationOptions, screenProps }
相反,如果我们使
navigationOptions
成为一个函数,那么 React Navigation 将使用包含{ navigation, navigationOptions, screenProps }
的对象调用它
So, you need to change your navigationOptions
to look like the following:因此,您需要将
navigationOptions
更改为如下所示:
static navigationOptions = ({ navigation }) => {
return {
// snip...
headerLeft:(
<TouchableOpacity onPress={() => navigation.toggleDrawer()} // remove "this.props" here
style={{padding:10}}>
<Icon size={27} name='ios-menu' color='#fff' />
</TouchableOpacity>
),
// snip...
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.