Steven Klinger
Steven Klinger

Reputation: 284

TouchableHighlight OnPress is not calling a function

I'm making an app in React Native and i have a problem that i don't understand.

In fact, when i press a button of my list, the onPress property related to this button don't call my function.

_onPressButton=() => {
   Alert.alert("Lol");
}

_renderRow (rowData, sectionID) {
return (
  <TouchableOpacity style={styles.row} onPress={() => this._onPressButton}>
    <Text style={styles.boldLabel}>{rowData.name}</Text>
    <Text style={styles.label}>{rowData.art}</Text>
  </TouchableOpacity>
)
}

This two functions are in my class, outside the render(). There is the render :

render () {
return (
  <View style={styles.container}>
    <ListView
      renderSectionHeader={this._renderHeader}
      contentContainerStyle={styles.listContent}
      dataSource={this.state.dataSource}
      renderRow={this._renderRow}
      renderFooter={this._renderFooter}
      enableEmptySections
      pageSize={15}
    />
  </View>
  )
 }
}

So when I press my button, nothing happens :/. Is someone have an idea please? Thanks for reading !

Upvotes: 1

Views: 5580

Answers (2)

Mohamed Saleh
Mohamed Saleh

Reputation: 3287

I think the correct way is to have both renderRow& onRowPress both binded on constructor like this:

  constructor (props) {
    super(props)

    this.renderRow = this.renderRow.bind(this)
    this.onRowPress = this.onRowPress.bind(this)

  } 

Then on renderRow

  renderRow (rowData) {
    return (
      <TouchableOpacity onPress={() => this.onRowPress(rowData)} >

      </TouchableOpacity>
    )
  }

Upvotes: 1

Pratish Shrestha
Pratish Shrestha

Reputation: 1902

You have not invoked the _onPressButton function. You can just pass this function on the onPress handler without using the arrow function, like this:

 onPress={this._onPressButton}

If you want to pass any parameters then you can wrap it around an arrow function.

onPress={() => {this._onPressButton('someParams')}}

P.S Your current code calls the onPress handler but does not invoke your _onPressButton function

 onPress={() => {this._onPressButton}} // _onPressButton is not invoked 
 you have to invoke it as:

 {() => {this._onPressButton()}} 

Upvotes: 3

Related Questions