React Native Navigation from Child Components

核能气质少年 提交于 2020-01-25 07:04:45

问题


I'm trying to implement a simple navigation between screens, but getting this error:

Undefined is not an object 'this.props.navigate'

AppNavigator.js

let AppNavigator = createStackNavigator({
  Signup: 
  { screen: SignupScreen, 
    navigationOptions: {
      header: null
    }

  },
  Login: { screen: LoginScreen,
    navigationOptions: {
      header: null
    } 
  },
},{
  initialRouteName: "Signup"
});

SignupScreen.js

<View>
 <SignupForm/>
</View>

SignupForm.js

const { navigate } = this.props.navigation;
<Text onPress={() =>
       navigate('Login')
}>
 ¿Allready have an account? Sign in
</Text>

I guess the problem is that there si something additional to do in child components cases. Please help.


回答1:


You should pass navigation to SignupForm. Choose 1 of 2 solution below

1.

<View>
 <SignupForm navigation={this.props.navigation} />
</View>

or

  1. in SignupForm.js
import { withNavigation } from 'react-navigation';

export default withNavigation(SignupForm);




回答2:


You must use withNavigation if you use separate component see the documentation about withNavigation : here




回答3:


You might have missed wrapping your AppNavigator in a NavigationContainer before using it elsewhere.

in your AppNavigator.js

import { createAppContainer } from 'react-navigation'; // add this
import { createStackNavigator } from 'react-navigation-stack'; // i trust you've already got this

let AppNavigator = createStackNavigator({
  Signup: 
  { screen: SignupScreen, 
    navigationOptions: {
      header: null
    }    
  },
  Login: { screen: LoginScreen,
    navigationOptions: {
      header: null
    } 
  },
},{
  initialRouteName: "Signup"
});

export default createAppContainer(AppNavigator); // this is important!

I actually don't think there's anything special you need to do for child components to work. That AppContainer is for ensuring correct props are passed to child components. Refer to documentation for a bit more context.



来源:https://stackoverflow.com/questions/59222652/react-native-navigation-from-child-components

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