2

how i can pass successfull and id for which touchable is passed.

for(var i = 0; i < datasource.length;i++){

var currentIndex = i;
this.viewCollection.push(

<TouchableHighlight onPress={() => this.handleItemTouch(currentIndex)} >

</TouchableHighlight>

 );
}

  handleItemTouch(i) {
  //i is every time equal to datasource.length

//based on "i" i want to scroll somewhere }

what i want to do is, that based on which touchablehighlight is pressed to scroll the scrollview to a x coordinate based on the "i" parameter

Kurt57
  • 17
  • 1
  • 5

2 Answers2

9

Since you're using var, the currentIndex variable isn't block scoped.

For example the first iteration will set the currentIndex to 1, so if you click on the touchablehighlight...it will be the correct index, but for every iteration after it will be updating the currentIndex on all the touchablehighlights.

This is why currentIndex will always be the length of the datasource on anyone of them you click. You can fix this by using let or if you use an iterator like forEach/map which will have different execution contexts.

for (let i = 0; i < datasource.length; i++){

this.viewCollection.push(

<TouchableHighlight onPress={() => this.handleItemTouch(i)} >

</TouchableHighlight>

 );
}
Matt Aft
  • 8,742
  • 3
  • 24
  • 37
5

You can use Function.prototype.bind for these matters. For example

<TouchableHighlight onPress={this.handleItemTouch.bind(this, currentIndex)} ></TouchableHighlight>

And then on your handleItemTouch:

handleItemTouch(index) {
    //do stuff
}
Emilio Rodriguez
  • 5,709
  • 4
  • 27
  • 32