简体   繁体   中英

React Native - useRef is giving null value on RNCamera

I am using react-native-camera for the first time and I am using functional component for that. I want to open the camera on button click but using the ref is not working. Here is my code :

const camContainer = () => {
  const cameraRef = useRef(null);

  useEffect(() => {
    console.log(cameraRef);
  }, [cameraRef]);

  const openCamera = () => {
    const options = {quality: 0.5, base64: true};
    // cameraRef.current.takePictureAsync(options);
    console.log(cameraRef);
  };

  return (
    <TouchableOpacity onPress={() => openCamera()}>
      <Text>Open Camera</Text>
      {!cameraRef && (
        <View>
          <RNCamera ref={cameraRef} style={{flex: 1, alignItems: 'center'}} />
        </View>
      )}
    </TouchableOpacity>
  );
};

I logged cameraRef using useEffect but the cameraRef.current was still null, I cannot understand how do I open the camera then ?

in docs of RNCamera, it should be like this

 <Camera ref={ref => { this.camera = ref; }} />; // ... snap = async () => { if (this.camera) { let photo = await this.camera.takePictureAsync(); } };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM