admin管理员组

文章数量:1289508

I am working on a React Native project using React Native 0.77.1 and trying to use the camera in my app. I have installed react-native-camera (version 4.2.1) and set up permissions correctly, but I am facing issues when trying to open the camera.

Problem:

  1. The camera opens but immediately closes.
  2. I get the error: "Attempt to invoke virtual method 'module.getEventDispatcher' on a null object reference"
  3. Sometimes, the camera just shows a loading indicator and does not open properly.

My Setup:

package.json

"dependencies": { "react": "18.3.1", "react-native": "0.77.1", "react-native-camera": "^4.2.1", "react-native-permissions": "^5.2.5", "react-native-qrcode-scanner": "^1.5.5" }

Android Permissions (AndroidManifest.xml)

Camera Component Code (CameraScreen.tsx)

 import React, { useState, useRef, useEffect } from 'react';
   import { View, Alert, Button, Platform } from 'react-native';
   import { RNCamera } from 'react-native-camera';
   import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';

     const CameraScreen = () => {
       const [hasPermission, setHasPermission] = useState<boolean | null>(null);
       const cameraRef = useRef<RNCamera>(null);

       useEffect(() => {
         const requestCameraPermission = async () => {
         const permission =
           Platform.OS === 'android'
            ? PERMISSIONS.ANDROID.CAMERA
            : PERMISSIONS.IOS.CAMERA;

         const result = await request(permission);
         setHasPermission(result === RESULTS.GRANTED);
       };

       requestCameraPermission();
     }, []);

     return (
       <View style={{ flex: 1 }}>
         {hasPermission ? (
           <RNCamera
            ref={cameraRef}
            style={{ flex: 1 }}
            type={RNCamera.Constants.Type.back}
            onCameraReady={() => console.log('Camera is ready')}
            captureAudio={false}
          />
        ) : (
          <Button title="Request Camera Permission" onPress={() =>        requestCameraPermission()} />
         )}
       </View>
     );
   };


export default CameraScreen;
  • Verified permissions (react-native-permissions returns GRANTED).
  • Ensured that the app has minSdkVersion 21 in android/build.gradle.
  • Manually linked react-native-camera using react-native link react-native-camera.
  • Cleaned and rebuilt the project using ./gradlew clean && react-native run-android.
  • Tried upgrading react-native-camera to the latest version.
  • Considered switching to react-native-vision-camera

本文标签: How to Properly Use Camera in React Native 077 (Latest Version)Stack Overflow