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>
);
}
});
Jakub Kučera
5784 silver badges21 bronze badges
asked Jan 18, 2016 at 17:39
Alien
3,6761 gold badge18 silver badges35 bronze badges
1 Answer 1
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.
answered Jan 18, 2016 at 17:41
Nader Dabit
53.8k14 gold badges110 silver badges91 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Alien
thanks for your answer, but get a error
undefined' is not an object (evaluating '_this._handlePress') :(lang-js