use*_*007 7 promise react-native react-native-camera
我试图在用户拍照后调用一个函数。我尝试通过以下方式这样做:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
拍照时出现以下错误:
错误:参考错误:doSomething 未定义
但是,如果我将 takePicture() 替换为:
takePicture() {
this.camera.capture()
.then(function(data) {
console.log(data.path);
})
.catch(err => console.error("error: " + err));
}
Run Code Online (Sandbox Code Playgroud)
记录了图像路径,并且没有发生错误。
您需要使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我使用了箭头函数来引用this回调中的正确内容。
或者你也可以像这样直接传递函数。
takePicture() {
this.camera.capture()
.then(this.doSomething)
.catch(err => console.error("error: " + err));
}
Run Code Online (Sandbox Code Playgroud)
但是,最后一种方法不会doSomething在正确的范围内运行,因为您需要doSomething使用箭头函数或在构造函数中使用bind. 第三种选择是使用装饰器使用 Babel 自动绑定方法。
祝你好运!
| 归档时间: |
|
| 查看次数: |
9662 次 |
| 最近记录: |