Reputation: 1481
I have a screen that shows a few items in list. my item are a component called CardItem which has couple of buttons. I implemented like above but when i run my project, component pass my desired data which is id to parent method in init status, but i need it when user click on that button.
Parent:
addItemQuantity = (id) => {
console.log('ADD item quantity with id: ', id);
};
render() {
return (
<CardItem
data={item}
index={idx}
key={item._id}
addItemQuantityPress={this.addItemQuantity}
/>
)
}
child:
handleAddItemQuantity = (id) => {
console.log('child component method');
this.props.addItemQuantityPress(id);
}
render() {
return (
<View style={styles.cardItemOperation} >
<TouchableHighlight
underlayColor="#ffffff"
onPress={this.handleAddItemQuantity(this.props.data._id)}
style={styles.icon} >
<Image
style={styles.icon}
resizeMode="contain"
source={require('./images/icon-add.png')} />
</TouchableHighlight>
</View>
)
}
Output when i run the project:
child component method
ADD item quantity with id: 5a2660924713cf6c8d088424
child component method
ADD item quantity with id: 5a1a58cacd0b8a0febce9fd7
child component method
ADD item quantity with id: 5a1a5856cd0b8a0febce9fd5
child component method
ADD item quantity with id: 5a4c8e9d2ebcf507323e7b73
child component method
ADD item quantity with id: 5a1a5862cd0b8a0febce9fd6
Upvotes: 0
Views: 1645
Reputation: 2521
As you have it written there,
this.handleAddItemQuantity(this.props.data._id)
Will get executed immediately at time of render. Change this to:
onPress={() => {this.handleAddItemQuantity(this.props.data._id)}}
That should do the trick
Upvotes: 1