【问题标题】:React - unable to use `this` to call component methods in callback function [duplicate]React - 无法使用`this`在回调函数中调用组件方法[重复]
【发布时间】: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/…

标签: reactjs exif-js


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2017-05-10
    • 2021-07-24
    相关资源
    最近更新 更多