我在用户拍摄图片后试图调用功能。我尝试以以下方式这样做:
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));
}
记录了图像路径,没有发生错误。
您需要使用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
,因为您需要使用箭头函数或使用bind
在构造函数中绑定doSomething
。第三种选择是使用装饰器使用babel自动启用该方法。
祝你好运!
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);
}
}