React Native 中的 Expo-camera 无法正常工作
2020-01-28
2151
我正在尝试使用 React Native 应用访问相机。我已经从官方文档中复制了所有代码。每个人都做了同样的事情,包括官方 expo-docs https://docs.expo.io/versions/latest/sdk/camera/ 。我访问相机并拍照的代码是
export default function Cameracontrol() {
const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
async function takePicture() {
console.log(this.camera)
if (this.camera) {
console.log('Pictactue Taken')
let photo = await this.camera.takePictureAsync();
}
else {
console.log('Caera Not Open');
}
}
useEffect(() => {
(async () => {
const { status } = await Camera.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
if (hasPermission === null) {
return <View />;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={type}
ref={camera => this.camera = camera}
>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<View style={{ flex: 1, flexDirection: "row", justifyContent: "space-between", margin: 20 }}>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}
onPress={() => {
setType(
type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back
);
}}>
<Ionicons
name="ios-photos"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={takePicture}
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}>
<FontAwesome
name="camera"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: 'transparent',
}}>
<MaterialCommunityIcons
name="camera-switch"
style={{ color: "#fff", fontSize: 40 }}
/>
</TouchableOpacity>
</View>
</View>
</Camera>
</View>
);
}
我遇到了以下错误。
undefined is not an object (evaluating '_this.camera = camera')
此错误与行密切相关
ref={camera => this.camera = camera}
通过删除此行代码,错误也会被删除。
如果有男孩能帮助我,我将不胜感激。
1个回答
您处在函数组件中,而不是类中。因此,您无法使用
this
。此外,
ref
无法像在类中那样工作。
您应该使用
useRef
:
https://reactjs.org/docs/hooks-reference.html#useref
const inputEl=useRef(null);
<input ref={inputEl} type="text" />
MBach
2020-01-28