React Native error "Cannot read Property 'navigate' of Undefined onPress

Asked

Viewed 45 times

-1

I’m having a problem in the code I’m trying to access a screen by pressing a button, so far so good but the problem is I’m trying to pass a props to the onPress, but this mistake is happening:

Typeerror: Cannot read Property 'navigate' of Undefined onPress C:/Users/21/projectTeste/screens/home.js:57 54 | 55 | Return( 56 | 57 | <TouchableOpacity style={this.styles.bntStyle} onPress={()=> this.props.navigation.navigate(this.props.screen)}> | ^ 58 | {this.props.titulo} 59 | {this.props.subTitulo} 60 | <Image style={this.styles.img} source={require('. /pictures/padlock.png')}/>

Basically I created a class called Bnt which is a button that receives several props and one of them is a props screen which receives just to which screen will pass to the onPress back in class Bnt of the above code.

Below is the class being used:

<Btn titulo='Módulo 1:' subTitulo='Fundamentos' left ='50' screen = 'modulo1'/>
                            
<Btn titulo='Módulo 2:' subTitulo='Hardware' screen = 'modulo2'/>

<Btn titulo='Módulo 3:' subTitulo='Software' screen = 'modulo3'/>

<Btn titulo='Módulo 4:' subTitulo='Internet' screen = 'modulo4'/>

Can someone help me with that?

1 answer

0

What happens is that the props "navigation" will exist only for the screens you reported when creating your routes. If you for example have a "home" screen in your route file, and it has a component to make the buttons, button components do not inherit navigation.

So that they can use "navigation", one of the solutions is to pass it as props to their component.

<Btn titulo='Módulo 1:' subTitulo='Fundamentos' left ='50' screen = 'modulo1' navigation = {this.props.navigation}/>

Doing this, your Btn component will be able to navigate to the screen you reported on the props "screen".

 <TouchableOpacity style={this.styles.bntStyle} onPress={()=> this.props.navigation.navigate(this.props.screen)}>
 <Image style={this.styles.img} source={require('./imagens/cadeado.png')}/>
 </TouchableOpacity>
  • Thanks Brother worked here, you’re 10.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.