React Navigation - cannot read property 'navigate' of undefined

谁说我不能喝 提交于 2019-12-13 13:56:08

问题


I've been trying to get up and running with react navigation but I run into a problem when I try to move navigation items into their own components.

HomeScreen.js

import React, { Component } from 'react';

import {
  StyleSheet,
  View,
  Text
} from 'react-native';

import NavButton from '../components/NavButton'

class HomeScreen extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>
        Hello World
        </Text>

        <NavButton
        navigate={this.props.navigator}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
});


export default HomeScreen;

Then in the NavButton component I try to navigate to the new screen.

 class NavButton extends Component {
  render() {
    return (
      <View>
        <Button
        title="Go to About"
        onPress={() => this.props.navigator.navigate('About')}
        />
      </View>
    );
  }
}
export default NavButton;

But I keep getting the error "Cannot read property 'navigate' of undefined.

Here is my Router.js file as well.

import React from 'react';
import {StackNavigator} from 'react-navigation';

import HomeScreen from '../screens/HomeScreen'
import AboutScreen from '../screens/AboutScreen'


export const AppNavigator = StackNavigator({
  Home: {
    screen: HomeScreen
  },
  About: {
    screen: AboutScreen
  }
})

回答1:


If you rename navigate={this.props.navigator} to navigator={this.props.navigation}, it should work because in NavButton you are calling this.props.navigator.navigate.




回答2:


An ordinary component that is not a screen component will not receive the navigation prop by default.

To resolve this exception, you could pass the navigation prop in to NavButton when you render it from a screen, like so: <NavButton navigation={this.props.navigation} />

Alternatively, we can use the withNavigation function to provide the navigation prop automatically


import { withNavigation } from 'react-navigation';

class NavButton extends React.Component {
  render() {
    return (
      <Button
        title="Back"
        onPress={() => {
          this.props.navigation.goBack();
        }}
      />
    );
  }
}

// withNavigation returns a component that wraps NavButton and passes in the
// navigation prop
export default withNavigation(NavButton);

refer: https://reactnavigation.org/docs/en/connecting-navigation-prop.html




回答3:


Make sure you are compiling ES6

if not simply use this.props.navigation or this.props.navigation.navigate whatever you need



来源:https://stackoverflow.com/questions/42793844/react-navigation-cannot-read-property-navigate-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!