7

我试图在用户拍照后调用一个函数。我尝试通过以下方式这样做:

export default class LA extends Component {
    constructor(props) {
      super(props);
      this.doSomething = this.doSomething.bind(this);
    }


    takePicture() {
      this.camera.capture()
      .then(function(data) {
        doSomething(data.path); //THIS CAUSES THE RUNTIME ERROR
      })
     .catch(err => console.error("error: " + err));
    }

    doSomething(imgPath) {
      console.log(imgPath);
    }


}

拍照时出现以下错误:

错误:参考错误:doSomething 未定义

但是,如果我将 takePicture() 替换为:

takePicture() {
  this.camera.capture()
  .then(function(data) {
    console.log(data.path);
  })
 .catch(err => console.error("error: " + err));
}

记录图像路径,并且不会发生错误。

4

2 回答 2

7

您需要使用this才能调用成员函数。这是一个工作示例:

export default class LA extends Component {
  constructor(props) {
    super(props);
    this.doSomething = this.doSomething.bind(this);
  }


  takePicture() {
    this.camera.capture()
    .then((data) => {
      this.doSomething(data.path);
    })
   .catch(err => console.error("error: " + err));
  }

  doSomething(imgPath) {
    console.log(imgPath);
  }


}

请注意,我this在回调中使用了箭头函数来引用正确的。

或者你也可以直接传递函数,像这样。

  takePicture() {
    this.camera.capture()
      .then(this.doSomething)
      .catch(err => console.error("error: " + err));
  }

但是,最后一种方法不会doSomething在正确的范围内运行,因为您需要doSomething使用箭头函数或在构造函数中使用bind. 第三种选择是使用装饰器使用 Babel 自动绑定方法。

祝你好运!

于 2017-03-01T04:41:44.900 回答
0
export default class LA extends Component {

  ...


  takePicture1() {
    this.camera.capture()
    .then((data) => {
      this.doSomething(data.path);   // CORRECT
      // keyword `this` represents instance of class LA
    })
   .catch(err => console.error("error: " + err));
  }


  takePicture2() {
    this.camera.capture()
    .then(function (data) {
      this.doSomething(data.path); // WRONG
      // function defines `this` as the global object 
      // (because it's where the function is executed)
    })
   .catch(err => console.error("error: " + err));
  }

  doSomething(imgPath) {
    console.log(imgPath);
  }
}
于 2018-05-23T07:33:11.273 回答