我正在尝试使用 Expo 的 Camera 对象拍照。
使用 Expo 25.0.0 和 React-native 0.52.0
我遇到的问题的简单示例代码如下:
import React from 'react';
import { Camera } from 'expo';
import { Text, View, TouchableOpacity } from 'react-native';
export default class App extends React.Component {
async press() {
console.log('Button Pressed');
if (this.camera) {
console.log('Taking photo');
let photo = await this.camera.takePictureAsync();
console.log(photo);
}
}
render() {
return (
<Camera
style={{ flex: 1 }}
ref={ (ref) => {this.camera = ref} }
>
<View style={{ flex: 1 }}></View>
<TouchableOpacity
style={{ flex: 0, backgroundColor: 'red' }}
onPress={this.press}
>
<Text>Touch Me</Text>
</TouchableOpacity>
</Camera>
);
}
}
发生的情况是:
- 显示相机 View
press()
回调被调用,但没有拍照- 如果我删除
if (this.camera)
检查,我会收到警告,[未处理的 promise 拒绝:TypeError: undefined is not an object (evaluating 'this.camera.takePictureAsync ')]
在我看来,从未进行过对相机对象的引用,但我似乎无法弄清楚为什么会出现这种情况,或者我所做的与文档不同。
最佳答案
绑定(bind)press
回调或使用箭头函数。
将 onPress={this.press}
替换为 onPress={this.press.bind(this)}
关于React-native refs 和 Expo Camera,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49229187/