reactjs - React - 无法使用`this`在回调函数中调用组件方法
问题描述
我是 React 的新手,目前正在开发一个使用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}/>
)
}
}
谢谢!
解决方案
您需要将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();
});
}
推荐阅读
- c# - 如何在 C# 和 ASP.NET MVC 中从视图访问数据到模型
- python - 当数据框列中的值为 x 时,使用 Jupyter Notebooks 和 Python 计算另一个列值为 y 的次数?
- matlab - 如何在 MATLAB 中从国际标准大气模型绘制多个图形?
- unity3d - 在运行时创建可编写脚本的对象 - 它创建实例但不将它们保存在资产文件夹中?
- python - 使用数组的 Seaborn 小提琴图 - 错误:`x` 和 `y` 变量似乎都不是数字
- ios - 是否可以添加带有多行文本的左栏按钮项
- flutter - Flutter web 执行“热重启”而不是“热重载”。Flutter Web 是否支持“热重载”?
- android - 神经网络 API 与芯片组 NPU api
- java - 这个正弦源代码有什么问题?
- c++ - 将 .txt 中的矩阵读入 C++