How to use onPress on a custom component?

Nick's answer is right.Along with that if you want to call separate function for both child and parent component then you can use onPressOut. This will help to manage state of componant

export default class Button extends Component {
  constructor(props){
    super(props)
  }

onClickListen = () => {
        if (this.state.isSelected === false) {
            this.setState({isSelected:true});
            isSelectedPass=true;
        }
        else {
            this.setState({isSelected:false});
            isSelectedPass=false;

        }
    }

  render(){
    return(
      <TouchableOpacity
      onPress={this.props.onPress} onPressOut={this.onClickListen}
      >
        <Text> Button </Text>
      </TouchableOpacity>
    )
  }
}

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

So, just found 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>
    )
  }
}

Long story short: since the onPress I'm passing is a prop in the MainPage, I'm passing it a function (this.doSomething) which later on is activated in Button's onPress.

Tags:

React Native