6

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>
 );
 }
});
asked Jan 18, 2016 at 17:39

1 Answer 1

9

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

answered Jan 18, 2016 at 17:41
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your answer, but get a error undefined' is not an object (evaluating '_this._handlePress') :(

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.