首页 > 解决方案 > 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}/>
        )
    }
}

谢谢!

标签: reactjsexif-js

解决方案


您需要将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();
  });
}

推荐阅读