首页 > 解决方案 > React Native - “未定义不是对象(评估'MyApp.navigation.openDrawer')

问题描述

我是 React Native 的初学者,我尝试制作菜单,但在调用 openDrawer 时出现此错误:

React Native - “未定义不是对象(评估'MyApp.navigation.openDrawer')onPress ..Router.js 37:60

这是一个嵌套菜单。

我的 Rooter.js :

import React from "react";
import { createStackNavigator, createDrawerNavigator } from "react-navigation";
import {
  Text,
  StyleSheet,
  Image,
  Button,
  TouchableHighlight
} from "react-native";
import Home from "../screens/Home";
import AddAnnounce from "../screens/AddAnnounce";
import Login from "../screens/Login";

const AddAnnounceStack = createStackNavigator({
  AddAnnounce: {
    screen: AddAnnounce
  }
});

const HomeStack = createStackNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      title: "   ACCUEIL",
      drawerLabel: "Home",
      drawerIcon: ({ tintColor }) => {
        <Image source={require("../icons/home.png")} style={[styles.icon]} />;
      },
      headerStyle: {
        backgroundColor: "#c51626",
        paddingLeft: 20,
        paddingRight: 20
      },
      headerTintColor: "#fff",
      headerTitleStyle: { fontWeight: "bold" },
      headerLeft: (
        <TouchableHighlight onPress={() => MyApp.navigation.openDrawer()}>
          <Image
            style={{ height: 30, width: 30 }}
            source={require("../icons/menu-button.png")}
          />
        </TouchableHighlight>
      ),
      headerRight: (
        <Image
          source={require("../icons/logoMenu.png")}
          style={{ width: 60, height: 50 }}
        />
      )
    }
  }
});

export const MyApp = createDrawerNavigator(
  {
    ACCUEIL: { screen: HomeStack },
    "Déposer une annonce": { screen: AddAnnounceStack }
  },
  { initialRoutName: "Home" }
);

我使用节点 8.11.3

我不明白这个错误是从哪里来的。

标签: javascriptandroidreactjsreact-native

解决方案


在您的 HomeStack 导航器中,将 navigationOptions 的类型替换为以参数 { navigation } 为参数的函数,并在您使用导航实例的地方使用此参数。

const HomeStack = createStackNavigator({
  Home: {
    screen: Home,
    navigationOptions: ({ navigation }) => ({
      title: "   ACCUEIL",
      drawerLabel: "Home",
      drawerIcon: ({ tintColor }) => {
        <Image source={require("../icons/home.png")} style={[styles.icon]} />;
      },
      headerStyle: {
        backgroundColor: "#c51626",
        paddingLeft: 20,
        paddingRight: 20
      },
      headerTintColor: "#fff",
      headerTitleStyle: { fontWeight: "bold" },
      headerLeft: (
        //replace MyApp.navigation by navigation above...
        <TouchableHighlight onPress={() => navigation.openDrawer()}>
          <Image
            style={{ height: 30, width: 30 }}
            source={require("../icons/menu-button.png")}
          />
        </TouchableHighlight>
      ),
      headerRight: (
        <Image
          source={require("../icons/logoMenu.png")}
          style={{ width: 60, height: 50 }}
        />
      )
    })
  }
});

推荐阅读