How to use onPress for a custom component?

Suppose I have this custom component:

export default class Button extends Component { render(){ return( <TouchOpacity> <Text> Button </Text> </TouchOpacity> ) } } 

And I use it in the parent component, for example:

 export default class MainPage extends Component { render(){ return( <Button onPress={ this.doSomething }></Button> ) } } 

For some reason (at least I donโ€™t know) this onPress will not even happen. I'm pretty new to reacting to battle. I believe I should find a way to enable this event handling.

Is it possible to get a small example of how to achieve this, based on my examples above?

+6
source share
1 answer

So, just figured out how to handle this.

 export default class Button extends Component { constructor(props){ super(props) } render(){ return( <TouchableOpacity onPress={this.props.onPress} > <Text> Button </Text> </TouchableOpacity> ) } } 

and

 export default class MainPage extends Component { render(){ return( <Button onPress={ ()=>this.doSomething }></Button> ) } } 

In short: since the onPress that I pass is a pillar in MainPage, I pass it the function ('() => this.doSomething'), which is later activated in Button onPress.

+14
source

All Articles