React Native onpress not working

onRadioPresseddoesn't seem to be called - what am I doing wrong? I also need to get the text contained in the clicked element.

I believe I can do this with help event.nativeEvent.text, right?

Thanks for any help.

class RadioBtn extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }

  onRadioPressed(event) {
    console.log('RADIOBUTTON PUSHED:');
  }

  render() {

    return (
        <View style={styles.radioGrp}>
            <View style={styles.radioContainer}>
                <TouchableHighlight onpress={() => this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
                    <Text style={styles.radio}>Left</Text>
                </TouchableHighlight>
            </View>
            <View style={styles.radioContainer}>
                <TouchableHighlight onpress={() => this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
                    <Text style={styles.radio}>Right</Text>
                </TouchableHighlight>
            </View>
        </View>
    );
  }
}
+4
source share
3 answers

So here:

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

First change onpressto onpress. Here () => this.onRadioPressed.bind(this)you specify an arrow function that returns another function this.onRadioPressed.bind(this), but you do not run it.

The correct ways are:

// 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 out this article https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.irpdw9lh0

+4
source

onpress:

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

:

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

, :

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

:)

+1

Use the line below

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

or using the arrow function

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

Source: https://habr.com/ru/post/1666785/


All Articles