react-native:undefined不是带有react导航的对象(评估'_this2.props.navigation')

时间:2018-11-07 17:09:09

标签: javascript react-native

我刚刚开始在react native中进行开发,遇到一个错误,我在应用程序中包含了Drawer导航,当在内容视图中点击它时,侧边菜单栏会打开,但是在那儿点击

<TouchableOpacity onPress={() =>this.props.navigation.toggleDrawer()}
                 style={{padding:10}}>
             <Icon  size={27} name='ios-menu' color='#fff' />
             </TouchableOpacity>

它会引发错误。

undefined is not an object (evaluating '_this2.props.navigation')

下面是我的脚本

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;

1 个答案:

答案 0 :(得分:1)

从反应导航documentation

  

尝试在<item name="@android:textColor">#ffffff</item>内使用this.props可能很诱人,但是由于它是组件的静态属性,因此navigationOptions并不引用该组件的实例,并且因此,没有道具可用。相反,如果我们使this为函数,那么React Navigation将使用包含navigationOptions

的对象来调用它

因此,您需要将{ navigation, navigationOptions, screenProps }更改为如下所示:

navigationOptions