0

I have an Arrow function inside my Class in react app specific and i want to call this function after pressed to Button so there is two way i don't understand differant between them

Code

selectPhotoTapped = () => {
    ImagePicker.showImagePicker(options, response => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled photo picker');
      } else {
        let source = {uri: response.uri};
        this.setState({
          avatarSource: source,
        });
      }
    });
  };

// First One 
 <TouchableOpacity onPress={this.selectPhotoTapped}>
      <Text>Upload</Text>
 </TouchableOpacity>


// Second One 

 <TouchableOpacity onPress={ () => this.selectPhotoTapped()}>
      <Text>Upload</Text>
 </TouchableOpacity>
Oliver D
  • 2,579
  • 6
  • 37
  • 80
  • 1
    The second version is necessary *if* the function isn't already bound to the current instance, because `() => this.selectPhotoTapped()` will result in the function being called with a calling context of the instance. But `selectPhotoTapped = () => {` already results in the function being bound to the instance, so `() => this.selectPhotoTapped()` isn't needed. If you had used method syntax instead, eg `selectPhotoTapped() {`, then `onPress={this.selectPhotoTapped}` wouldn't work, because the function wouldn't be invoked with the right calling context (unless you used `.bind` in the constructor) – CertainPerformance Dec 06 '19 at 10:44
  • 1
    So if you're using class field syntax with `selectPhotoTapped = () => {`, feel free to keep using `onPress={this.selectPhotoTapped}`, it's the most concise – CertainPerformance Dec 06 '19 at 10:46

0 Answers0