React Native onpress not working

You can not bind the function inside onpress link this :

<TouchableHighlight onpress={() => this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>

use it like this :

<TouchableHighlight onpress={() => this.onRadioPressed()} underlayColor='#f1c40f'>

if you want to bind the function then try this:

<TouchableHighlight onpress={this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>

Cheers:)


if https://stackoverflow.com/a/41651845/9264008 doesn't works check the way you have imported TouchableOpacity

correct import import { TouchableOpacity } from 'react-native'

sometimes mistakenly weird import happens example below

❌ Import import { TouchableOpacity } from 'react-native-gesture-handler'


So here:

<TouchableHighlight onpress={() => this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
    <Text style={styles.radio}>Left</Text>
</TouchableHighlight>

First change onpress to onPress. Here () => this.onRadioPressed.bind(this) you are specifying an arrow function that returns another function this.onRadioPressed.bind(this) but you never trigger it.

Correct ways:

// You can do either this
<TouchableHighlight onPress={() => this.onRadioPressed()} underlayColor='#f1c40f'>
    <Text style={styles.radio}>Left</Text>
</TouchableHighlight>

// Or you can do either this
<TouchableHighlight onPress={this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
    <Text style={styles.radio}>Left</Text>
</TouchableHighlight>

I would recommend checking this article out https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.irpdw9lh0


Use below line

<TouchableHighlight onPress={this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>

or using arrow function

<TouchableHighlight onPress={() => this.onRadioPressed()} underlayColor='#f1c40f'>

Tags:

React Native