Thai Tran
Thai Tran

Reputation: 9935

React native - Binding event in row of ListView

I cannot find the correct way in order to trigger the event from the class based definition under the row of the list view. Here is what i come so far

class SampleApp extends React.Component {

  constructor(props){
    super(props)
    this.state = {
        dataSource: ds.cloneWithRows(this._partners()),
    }

    // this._click = this._click.bind(this);
  }

 _click() {
    console.log('clicked');
  }

  _renderRow(rowData) {
    return (<TouchableHighlight onPress={() => {this._click();}}>
        <Text style={{ fontSize:18 }}>{rowData}</Text>
      </TouchableHighlight>);
  }

  render() {
    console.log('Partners: ', this._partners() )
    return (
      <View style={styles.container}>
        <ListView
         dataSource={this.state.dataSource}
         renderRow={ this._renderRow } />
      </View>
    );
  }
}

this inside onPress is not referred to react component. How can I fix it ? This is the react playground link https://rnplay.org/apps/Xd-l3w

Upvotes: 3

Views: 2401

Answers (1)

Zidail
Zidail

Reputation: 620

Try this.

constructor(props){
  super(props)
  this.state = {
    dataSource: ds.cloneWithRows(this._partners()),
  }

  this._renderRow = this._renderRow.bind(this);
}

_renderRow() doesn't contain the scope. Rebinding it fixes the issue.

onPress={this._click} will also work instead of putting the this._click in another function.

Here's a fork of your code.

Upvotes: 5

Related Questions