React Navigation - 无法读取undefined的属性'navigate'

时间:2017-03-14 18:30:39

标签: javascript react-native react-navigation

我一直试图使用react navigation启动并运行,但是当我尝试将导航项目移动到他们自己的组件中时,我遇到了一个问题。

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;

然后在NavButton组件中,我尝试导航到新屏幕。

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

但是我一直收到错误“无法读取未定义的属性'导航'。

这也是我的Router.js文件。

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
  }
})

4 个答案:

答案 0 :(得分:7)

如果您将navigate={this.props.navigator}重命名为navigator={this.props.navigation},它应该有效,因为在NavButton中您正在调用this.props.navigator.navigate

答案 1 :(得分:0)

不是屏幕组件的普通组件默认情况下不会接收导航道具。

要解决此异常,可以在从屏幕上渲染导航道具时将其传递给NavButton,例如:<NavButton navigation={this.props.navigation} />

或者,我们可以使用withNavigation函数自动提供导航道具


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);

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

答案 2 :(得分:0)

确保您正在编译ES6

如果不是简单地使用this.props.navigation 要么 this.props.navigation.navigate 无论您需要什么

答案 3 :(得分:0)

import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function GoToButton() {
  const navigation = useNavigation();

  return (
    <Button
      title='Screen Name'
      onPress={() => navigation.navigate(screenName)}
    />
  );
}

您可以在 React Navigation v 5.x 中使用来自 @react-navigation/native 的 useNavigation。 documentation 中的更多详细信息。