找不到变量:使用反应导航导航

Can't find variable: Navigate with react-navigation

我在同一个 index.android.js 文件中有这个简单的代码:

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

// First Page
class FirstPage extends Component {
  static navigationOptions = {
    title: 'Welcome',
  };

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <Text>Hello First Page</Text>
        <Button 
          onPress={() => navigate('SecondPage')}
          title="Go to second page"
        />
      </View>
    );
  }
}

// Second Page
class SecondPage extends Component {
  static navigationOptions = {
    title: 'Second Page',
  };

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <Text>Hello Second Page</Text>
        <Button 
          onPress={() => navigate('FirstPage')}
          title="Go to first page"
        />
      </View>
    );
  }
}


const SimpleApp = StackNavigator({
  FirstPage: { screen: FirstPage},
  SecondPage: { screen: SecondPage},
});

AppRegistry.registerComponent('MoviesTickets_YCH', () => FirstPage);

我只想在屏幕之间导航,但出现错误消息:找不到变量:导航,我不知道为什么会这样,知道怎么回事吗?

感谢您的帮助

在渲染方法中添加以下内容:

const {navigate} =this.props.navigation;

你的渲染应该是这样的

render(){
const {navigate} =this.props.navigation;
return (
  .... ) ;
}

在您使用导航的每个组件中。 有关更多信息,请按照文档进行操作,这非常简单。 reactnavigation

如果我清楚的话,React 本机文档说 navigate 它是一个动作创建器,您可以在 this.props.navigation;

中访问它

const { navigate } = this.props.navigation; 在渲染中。

remove node_modules and package-lock.json
npm install
npm install --save react-navigation
npm install --save react-native-gesture-handler
react-native link