Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native onpress not working

Tags:

react-native

onRadioPressed does not seem to be called - what am I doing wrong? I also need to get the text contained in the 'clicked' item.

I believe I can get that with event.nativeEvent.text, correct?

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>
    );
  }
}
like image 377
miarde Avatar asked Jan 14 '17 15:01

miarde


1 Answers

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

like image 200
Vyacheslav A. Avatar answered Oct 15 '22 14:10

Vyacheslav A.