我对反应相当陌生,目前正在进行一个使用exif-js库读取图像EXIF数据的项目,请参阅下面的示例代码。EXIF.getData(file, callback)是从这个库中读取给定图像并在回调中执行其他一些任务的方法。在我的组件中,我定义了一个函数(doSomething),用于回调。但是,当我试图调用函数this.doSomething()时,它会抛出错误:this.doSomething is not a function。
在他们的文档中,他们解释了In the callback function you should use "this" to access the image...,所以看起来this被用来引用回调中的文件,这就是为什么文件对象上没有这样的方法。
所以问题是:如果this是指库回调中的其他函数,那么如何在同一个组件中调用我的其他函数?
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}/>
)
}
}谢谢!
发布于 2021-06-13 23:19:45
您需要将类的this绑定到doSomething处理程序。这可以在构造函数中完成。
constructor(props) {
super(props);
...
this.doSomething = this.doSomething.bind(this);
}或者更容易定义为箭头函数。
doSomething = () => {
console.log("...");
}然后,可以保存对类组件外部this的引用,以便在回调范围内关闭。
handleChange = (e) => {
const self = this;
var file = e.target.files[0];
EXIF.getData(file, function () {
console.log(this.exifdata);
self.doSomething();
});
}https://stackoverflow.com/questions/67963316
复制相似问题