Ad

React Native Loop This

- 1 answer

when I put onPress in a map loop, it doesn't work. how to fix it?

var PageOne = React.createClass({
  _handlePress() {
    this.props.navigator.push({id: 2,});
  },
  render () {
      return (
        <View>          
          <TouchableOpacity onPress={this._handlePress}> //work here 
          <Text> One </Text>
          </TouchableOpacity>
          <View style={styles.albums}>
          {
            list.map(function(item, index){
              return (
                <TouchableOpacity key={index} onPress={this._handlePress}> //doesn't work hehre
                  <Text>{item}</Text>
                </TouchableOpacity>
              )
            })
          }
            </View>
      </View>
      );
  }
});
Ad

Answer

this is referring to the wrong context, you need the scope to be lexically bound, which is what the fat arrow function will do for you.

Try calling your function like this:

onPress={ () => this._handlePress() }

Also, you need to bind the map function to the correct context like this:

<View style={styles.albums}>
  {
    list.map(function(item, index){
       return (
         <TouchableOpacity key={index} onPress={() => this._handlePress()}> 
           <Text>{item}</Text>
          </TouchableOpacity>
       )
     }.bind(this))
   }
</View>

Or like this:

<View style={styles.albums}>
  {
    list.map((item, index) => {
       return (
         <TouchableOpacity key={index} onPress={() => this._handlePress()}> 
           <Text>{item}</Text>
         </TouchableOpacity>
       )
     })
   }
</View>

I set up a working project here.

https://rnplay.org/apps/_PmG6Q

Ad
source: stackoverflow.com
Ad