在takePictureAsync时未定义ReactNative this.camera

时间:2020-02-23 13:29:53

标签: react-native expo

我总是在this.camera上不确定,下面这段代码出了什么问题。
我正在尝试使用世博相机拍摄图片并将其渲染到视图中
任何人都可以提供帮助,谢谢

import React, { useEffect, Component, useState } from "react";
import { Text, View, TouchableOpacity } from "react-native";
import { Camera } from "expo-camera";


export default class App extends Component<any, any> {
  camera: Camera;

  constructor(props) {
    super(props)

    this.state = {
      hasPermission: null,
      type: Camera.Constants.Type.back
    }
  }

  componentDidMount() {
    this.requestCameraPermission();
  }

  requestCameraPermission = async() => {
    const {status } = await Camera.requestPermissionsAsync();
    this.setState({ hasPermission: status === 'granted'})
  }

  async takeSnapshot()
  {
    console.log(this.camera) // this always undefined
    let options = { quality: 1, base64: true, fixOrientation: true, exif: true };
    let photo = await this.camera.takePictureAsync(options)
    console.log(photo)
    console.log(photo.uri)
  }

  render() {
    if (this.state.hasPermission === null) {
      return <View />
    }
    else if (this.state.hasPermission === false) {
      return <Text>No access to camera</Text>
    }
    else {
      return(
        <View style={{ flex: 1 }}>
          <Camera style={{ flex: 1 }} type={ this.state.type } ref={(cam) => { this.camera = cam; console.log(this.camera) }} >
            <View style={{
              flex: 1,
              backgroundColor: "transparent",
              flexDirection: "row"
            }}>
              <View style={{ flex: 1, height: 80, alignSelf: "flex-end", alignItems: "stretch", backgroundColor: "white" }}>
                <TouchableOpacity style={{
                    alignSelf: "center",
                    borderWidth: 1,
                    borderColor: "rgba(0, 0, 0, 0.2)",
                    alignItems: "center",
                    justifyContent: "center",
                    width: 50,
                    height: 50,
                    backgroundColor: "black",
                    borderRadius: 50,
                    marginTop: 10
                }}
                onPress={ this.takeSnapshot }>
                </TouchableOpacity>
              </View>
            </View>
          </Camera>
        </View>
        )
    }
  }
}

0 个答案:

没有答案