React Native loop this

when i put onPressthe cards in the 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>
      );
  }
});
+4
source share
1 answer

this refers to the wrong context, you need a lexical binding region, and this is what the thick arrow function does for you.

Try calling your function as follows:

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

In addition, you need to bind the map function to the correct context, for example:

<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 created a working draft here .

https://rnplay.org/apps/_PmG6Q

+6
source

Source: https://habr.com/ru/post/1624833/


All Articles