Expo-Camera报错:Cannot read property 'Type' of undefined 求解
解决expo-camera中Camera.Constants.Type未定义的问题
你遇到的Cannot read property 'Type' of undefined和Unresolved variable Constants错误,核心原因是expo-camera的API在新版本中做了调整——原来挂载在Camera对象下的Constants属性已被移除,换成了单独导出的枚举类型。
具体修复步骤:
- 更新导入语句,新增
CameraType的导入:
import { Camera, CameraType } from 'expo-camera';
替换所有旧API引用:
- 初始化相机类型的代码:
原代码:
改为:const [type, setType] = useState(Camera.Constants.Type.back);const [type, setType] = useState(CameraType.back); - 翻转相机的判断逻辑:
原代码:
改为:setType( type === Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back );setType( type === CameraType.back ? CameraType.front : CameraType.back );
- 初始化相机类型的代码:
若仍有问题,检查依赖并重新安装:
确保expo-camera为最新兼容版本,执行命令:
npx expo install expo-camera
修改后的完整代码:
import React, { useState, useEffect } from 'react'; import { Text, View, TouchableOpacity, StyleSheet, Image } from 'react-native'; import { Camera, CameraType } from 'expo-camera'; export default function CameraComponent() { const [hasPermission, setHasPermission] = useState(null); const [cameraRef, setCameraRef] = useState(null); const [type, setType] = useState(CameraType.back); const [photo, setPhoto] = useState(null); useEffect(() => { (async () => { const { status } = await Camera.requestCameraPermissionsAsync(); setHasPermission(status === 'granted'); })(); }, []); if (hasPermission === null) { return <View />; } if (hasPermission === false) { return <Text>No access to camera</Text>; } const takePicture = async () => { if (cameraRef) { let photo = await cameraRef.takePictureAsync(); setPhoto(photo.uri); } }; return ( <View style={styles.container}> <Camera style={styles.camera} type={type} ref={ref => setCameraRef(ref)}> <View style={styles.buttonContainer}> <TouchableOpacity style={styles.button} onPress={() => { setType( type === CameraType.back ? CameraType.front : CameraType.back ); }}> <Text style={styles.text}> Flip </Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={takePicture}> <Text style={styles.text}> Snap </Text> </TouchableOpacity> </View> </Camera> {photo && ( <View style={styles.previewContainer}> <Text style={styles.previewText}>Preview:</Text> <Image source={{ uri: photo }} style={styles.previewImage} /> </View> )} </View> ); }
内容的提问来源于stack exchange,提问作者Klau
相关产品推荐
相关产品推荐

