React Navigation - 无法读取未定义的 属性 'navigate'

React Navigation - cannot read property 'navigate' of undefined

我一直在尝试起床 运行 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;

但我不断收到错误消息“无法读取未定义的 属性 'navigate'。

这也是我的 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
  }
})

如果您将 navigate={this.props.navigator} 重命名为 navigator={this.props.navigation},它应该可以工作,因为在 NavButton 中您调用的是 this.props.navigator.navigate.

非屏幕组件的普通组件默认不会接收导航属性。

要解决此异常,您可以在从屏幕呈现时将导航道具传递给 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

确保你编译的是 ES6

如果不是简单地使用this.props.navigation 要么 this.props.navigation.导航 随便你

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/native 的 useNavigation 与 React Navigation v 5.x 结合使用。 documentation.

中有更多详细信息