I'm fairly new to React and currently working on a project that uses exif-js
library to read image EXIF data, see sample code below. EXIF.getData(file, callback)
is the method from this library for reading the given image and performing some other tasks in the callback. In my component, I defined a function (doSomething
) to be used by the callback. But when I try to call the function this.doSomething()
, it throws error: this.doSomething is not a function
.
In their documentation, they explained that In the callback function you should use "this" to access the image...
, so it looks like this
is being used to refer the file inside the callback, that's why there is no such method on the file object.
So question is: how do I call my other functions in the same component, if this
is referring to something else in the library callback?
import React, { Component } from 'react';
import EXIF from "exif-js"; // https://github.com/exif-js/exif-js/blob/HEAD/exif.js
export default class QuestionComponent extends Component {
handleChange = (e) => {
var file = e.target.files[0];
EXIF.getData(file, function () {
console.log(this.exifdata);
this.doSomething(); // <====== fails here
});
}
// how to call this method from the callback function above?
doSomething () {
console.log("...");
}
render() {
return (
<input type="file" id="file" onChange={this.handleChange}/>
)
}
}
Thanks!
You need to bind this
of the class to the doSomething
handler. This can be done in the constructor
constructor(props) {
super(props);
...
this.doSomething = this.doSomething.bind(this);
}
or more easily defined as an arrow function.
doSomething = () => {
console.log("...");
}
Then you can save a reference to the outer this
of the class component to close over in the callback scope.
handleChange = (e) => {
const self = this;
var file = e.target.files[0];
EXIF.getData(file, function () {
console.log(this.exifdata);
self.doSomething();
});
}