【发布时间】:2021-08-29 22:48:39
【问题描述】:
我是 React 的新手,目前正在开发一个使用 exif-js 库读取图像 EXIF 数据的项目,请参阅下面的示例代码。 EXIF.getData(file, callback) 是该库中用于读取给定图像并在回调中执行一些其他任务的方法。在我的组件中,我定义了一个供回调使用的函数 (doSomething)。但是当我尝试调用函数this.doSomething()时,它会抛出错误:this.doSomething is not a function。
在他们的documentation 中,他们解释说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}/>
)
}
}
谢谢!
【问题讨论】:
-
尝试在组件的构造函数中绑定
handleChange函数,即this.handleChange = this.handleChange.bind(this);。 reactjs.org/docs/…