React native - undefined不是一个对象('评估this.props.navigation')

时间:2018-06-02 21:34:55

标签: react-native tabs navigation expo drawer

预期行为:应打开一个抽屉,其中包含标题中的菜单图标。

当前行为:错误消息undefined is not an object ('evaluating this.props.navigation')

搜索错误并没有帮助我。

我将导航分成两个文件: RootNavigation.js MainTabNavigation

RootNavigation.js

const AppNavigator = createSwitchNavigator({

  Main: MainTabNavigator,
});
const DrawerStack = createDrawerNavigator({
  Home: {
    screen: AppNavigator
  },
  Login: {
    screen: login
  },
  Signup: {
    screen: signup
  }
});

export default class RootNavigation extends React.Component {
  componentDidMount() {
    this._notificationSubscription = this._registerForPushNotifications();
  }

MainTabNavigation.js

const HomeStack = createStackNavigator({
  Home: HomeScreen,
});

HomeStack.navigationOptions = {
  tabBarLabel: 'Home',
  tabBarIcon: ({ focused }) => (
    <TabBarIcon
      focused={focused}
      name={
        Platform.OS === 'ios'
          ? `ios-home${focused ? '' : '-outline'}`
          : 'md-home'
      }
    />
  ),   
};

const LinksStack = createStackNavigator({
  Links: LinksScreen,
});

LinksStack.navigationOptions = {
  tabBarLabel: 'Shops',
  tabBarIcon: ({ focused }) => (
    <TabBarIcon
      focused={focused}
      name={Platform.OS === 'ios' ? `ios-list${focused ? '' : '-outline'}` : 'md-list'}
    />
  ),
};

const SettingsStack = createStackNavigator({
  Settings: SettingsScreen,
});

SettingsStack.navigationOptions = {
  tabBarLabel: 'Cart',
  tabBarIcon: ({ focused }) => (
    <TabBarIcon
      focused={focused}
      name={Platform.OS === 'ios' ? `ios-cart${focused ? '' : '-outline'}` : 'md-cart'}
    />
  ),
};

export default createBottomTabNavigator({
  HomeStack,
  LinksStack,
  SettingsStack,
});

MainTab 文件,在标题

中显示一个图标
static navigationOptions = ({navigation}) =>({
  title: 'Home',
  headerLeft: <Ionicons 
                name="md-menu" 
                size={25} 
                color="blue" 
                style={{ margin: 7,}}
                onPress={() => this.props.navigation.navigate('DrawerOpen')} 
                />
});

2 个答案:

答案 0 :(得分:1)

如文档here中所述,当navigationOptions用作函数时,this不引用组件的实例;所以this.props不可用。

相反,您需要替换:

this.props.navigation.navigate('DrawerOpen')

使用:

navigation.navigate('DrawerOpen')

或者,您可能希望使用示例here中显示的navigation.openDrawer()帮助器,因为导航到DrawerOpen意味着您要导航到具有该名称的屏幕。< / p>

答案 1 :(得分:0)

当你像这样创建组件女巫时,你必须知道这个

class MyComponent extends ....

如果你想使用任何道具,你必须写这个KeyWord例如

this.props.navigation.nvigate()

但是如果您创建具有箭头功能的组件

const Mycomponent = (props) => {}

你不需要这个KeyWord和你必须像这样写的道具

 props.navigation.navigate()

并且在你的情况下,如果在导航选项中使用组件你不需要这个或道具KeyWord,只需写

 navigation.navigate()