You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-native-vision-camera无法拍照:handleCapture函数未触发

问题排查与修复方案

1. 拍照按钮点击无响应的核心原因

你的拍照按钮TouchableOpacity样式里加了**flex:1**,这在绝对定位元素上完全多余,还会导致按钮点击区域异常,甚至被上层Camera组件拦截点击事件。直接删掉flex:1即可:

<TouchableOpacity
  onPress={handleCapture}
  style={{
    height: 50,
    width: 50,
    borderRadius: 30,
    backgroundColor: 'red',
    position: 'absolute',
    bottom: 50,
    alignSelf: 'center',
  }}
></TouchableOpacity>

2. 修复Camera组件初始化问题

你没有判断device是否有效就渲染Camera,会导致组件无法正确初始化,mycam.current可能为null。添加device != null的判断:

{isCameraVisible && device != null && (
  <View style={StyleSheet.absoluteFill}>
    <Camera
      style={{flex: 1}}
      autoFocus="on"
      photo={true}
      device={device}
      isActive={isCameraVisible}
      ref={mycam}
    />
    {/* 拍照按钮 */}
  </View>
)}

3. 修正handleCapture的判断逻辑

原代码里if (mycam != null)逻辑错误,mycam是useRef创建的对象永远不会为null,应该判断它的current属性:

const handleCapture = async () => {
  console.log('handlecapture run');
  if (mycam.current != null) {
    try {
      const photo = await mycam.current.takePhoto();
      console.log('CAMERAPIC:     ', photo.path);
      setNewPic(photo.path);
      addPic();
      setIsCameraVisible(false);
      toggleModal();
    } catch (err) {
      console.error('拍照失败:', err);
    }
  }
};

4. 解决HNG RISK提示

紫色的HNG RISK是Vision Camera的权限风险提示,需要完成以下配置:

  • 在iOS的Info.plist中添加相机权限描述:
    <key>NSCameraUsageDescription</key>
    <string>需要访问相机来拍摄报告照片</string>
    
  • 在组件挂载时主动请求权限:
    useEffect(() => {
      const requestCameraPermission = async () => {
        const permission = await Camera.requestCameraPermission();
        if (permission !== 'authorized') {
          alert('需要相机权限才能拍照');
        }
      };
      requestCameraPermission();
    }, []);
    

内容的提问来源于stack exchange,提问作者Blnk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:52:05