React native nested navigation——获取导航上下文

React native nested navigation- getting navigation context

我正在尝试构建一个简单的嵌套导航器,即堆栈导航中的选项卡导航。我得到:

"undefined is not an object- evaluating this.props.navigation"

尝试通过下面的 "myFunction" 导航堆栈时。我尝试了另一种方法,即通过导航选项的 "headerright" 实现堆栈导航 - 它有效。但我真的很想通过内容部分的按钮来实现它。代码如下,显示了两种导航方法:

import React, { Component } from 'react';
    import {
      AppRegistry,
      Text, View, Button, Image,  StyleSheet
    } from 'react-native';
    import { TabNavigator, StackNavigator } from "react-navigation";

    class RecentChatsScreen extends React.Component {

       static navigationOptions = ({ navigation }) => ({
        title: `Recent Chats`,
        headerRight: <Button title="Go Chat" onPress={() => navigation.navigate('Chat', { user: 'Lucy' })}/>,
      });

    myFunction() {
        const { navigate } = this.props.navigation;
        navigate('Chat', { user: 'Lucy' });
    }

      render() {

        return (
        <View>
        <Text>List of recent chats</Text>
         <Button
              onPress={        
    this.myFunction
    }
              title="Go Chat."
            />
            </View>
            );
      }
    }

    class ChatScreen extends React.Component {
       static navigationOptions = {
        title: 'chat screen',
      };

      render() {
        return <Text>Chat screen</Text>
      }
    }

    class AllContactsScreen extends React.Component {
      render() {
        return <Text>List of all contacts</Text>
      }
    }

    const MainScreenNavigator = TabNavigator({
      Recent: { screen: RecentChatsScreen },
      All: { screen: AllContactsScreen },
    });

    MainScreenNavigator.navigationOptions = {
      title: 'My Chats',
    };

    const SimpleApp = StackNavigator({
      Home: { screen: MainScreenNavigator },
      Chat: { screen: ChatScreen },
    });

    AppRegistry.registerComponent('SimpleApp', () => SimpleApp);

您可能忘记了 绑定 this,因此当调用 myFunction 时它不在 class RecentChatsScreen 范围内。

尝试添加这个

class RecentChatsScreen extends React.Component {
    constructor(props) {
        super(props);
        this.myFunction = this.myFunction.bind(this);
    }
}