简体   繁体   中英

Can't understand onPress behaviour TouchableOpacity by calling function in different ways

I have a react-native class component, in which I have a counter function:

counter() {
  console.log("hi")
  this.setState({count:this.state.count+1})
}

I have a state named count initialized to 0. I have a text which displays the count value as well.

In my render, in the return, im trying to call this counter function onPress of a TouchableOpacity. I tried 2 things in the onPress with 2 different outputs. Can someone explain why i got these outputs for each case? :

  1. onPress = {() => this.counter()}

here, state value was updating and displaying, and i got the console.log as well (desired output)

  1. onPress = {this.counter}

here, i got the console.log, but the state value wasn't updating. why isnt state updating here?

Thanks in advance

If you want to call counter function without arrow pattern in class component then you need to call bind in constructor block for counter function

constructor(props) {
    super(props);
    this.counter = this.counter.bind(this);
}

counter() {
    this.setState({ count: this.state.count + 1 });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM