我试图在用户拍照后调用一个函数。我尝试通过以下方式这样做:
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);
}
}
拍照时出现以下错误:
error: Reference Error: doSomething is not defined
但是,如果我将 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
到类,使用箭头函数或在构造函数中使用bind
.第三种选择是使用装饰器使用 Babel 自动绑定(bind)方法。祝你好运!
关于.then 异步函数中的 React-Native 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42523110/