Search code examples
react-nativetouchableopacityonpress

react-native : onPress doesn't work


I work on an onPress event on react native. At a first time, I wrote that code :

<TouchableOpacity
    onPress={(this.props.minimum==null||this.props.value-1>=this.props.minimum)
        ? this.props.onDecrement
        :console.log(this.props.texte+" : minimum atteint")}
    style={[buttonSpinner,buttonSpinnerLeft]}>

With that, my button works, but onPress is called automatically on each render() call. I search and I found a solution here : React Native onPress being called automatically.

But now, if I don't have any automatic call... I don't have call when I press on my Touchable component.

I try some versions :

const p=this.props;
//some other code
<TouchableOpacity
    onPress={()=>(p.minimum==null||p.value-1>=p.minimum)
        ? p.onDecrement
        :console.log(p.texte+" : minimum atteint")}
    style={[buttonSpinner,buttonSpinnerLeft]}>

--

const p=this.props;
// some other code
<TouchableOpacity
    onPress={(p)=>(p.minimum==null||p.value-1>=p.minimum)
        ? p.onDecrement
        :console.log(p.texte+" : minimum atteint")}
    style={[buttonSpinner,buttonSpinnerLeft]}>

--

<TouchableOpacity
    onPress={()=>(this.props.minimum==null||this.props.value-1>=this.props.minimum)
        ? this.props.onDecrement
        :console.log(this.props.texte+" : minimum atteint")}
    style={[buttonSpinner,buttonSpinnerLeft]}>

Without success...

Precision, I work on a separated component. This component is called in a main render like that :

<NumberSpinner
    onDecrement = {()=>this.onDecrement(elt.idCat,idElt)}
    onIncrement = {()=>this.onIncrement(elt.idCat,idElt)}
    minimum = {0}
    maximum = {null}
    texte = {elt.slug}
    value={elt.qteTxt}
/>

Solution

  • Try to move your logic in a function so use the onPress with a function call only

    <TouchableOpacity
             onPress={this.onPress}
           >
       <Text> Touch Here </Text>
    </TouchableOpacity>
    

    and your function:

    onPress = () => {
       //your logic here
      }