I'm trying to call the remove function that is in my ShoppingCartScreen component in my CartList component. I also want to pass in values from the CartList component class. I kept getting issues when I tried to call the add in my CartList class.
export default class ShoppingCartScreen extends Component {
remove = (qty) => {
let q = qty
if (q > 1) {
q = q - 1;
this.setState({ qty: q })
}
}
render() {
return (
<View>
<ScrollView backgroundColor='#bbb'>
<CartList
remove = {this.remove} />
</ScrollView>
</View>
)
}
export default class CartList extends Component {
render() {
return (
<View>
<TouchableOpacity onPress={this.props.add(this.state.qty)}>
<Icon
name="md-close"
size={25}
color='black'
style={{ height: 25, width: 25 }}
iconStyle={{ marginRight: 0 }}/>
</TouchableOpacity>
</View>
)
}
CodePudding user response:
First, you pass remove
to the CartList
and then inside call this.props.add
, so you need to change the name. Second, you need to upgrade this.props.remove
call to an arrow function:
<TouchableOpacity onPress={() => this.props.remove(this.state.qty)}>
onPress
expects that you pass a function to be called. When the component is rendered, the this.props.add(this.state.qty)
gets evaluated immediately because it is already a function call. This is why you must use an arrow function is this case.