反作用导航-不能读取未定义的属性“导航”

[英]React Navigation - cannot read property 'navigate' of undefined


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.

我一直在尝试使用react导航条来启动和运行,但当我试图将导航项移动到它们自己的组件中时,我遇到了一个问题。

HomeScreen.js

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.

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

 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.

这是我的路由器。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
  }
})

2 个解决方案

#1


6  

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.

如果您重命名导航= { this.props。导航}导航器= { this.props。导航},它应该工作,因为在导航按钮中,你调用这个。props.navigator。导航。

#2


0  

  1. Declare the Navigation in props:-
  2. 在道具中声明导航:-
constructor(props) {
      super(props);
      this.navigate = this.props.navigation.navigate;      
    }
  1. Use:-
  2. 使用:

this.navigate('Screen Name');

这一点。导航(“账户名”);


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/03/14/e6c9168e5ea8346e427093300ec9fb28.html



 
  © 2014-2022 ITdaan.com 联系我们: