React-native refs 和 Expo Camera

标签 react-native expo

我正在尝试使用 Expo 的 Camera 对象拍照。

使用 Expo 25.0.0 和 React-native 0.52.0

我遇到的问题的简单示例代码如下:

import React from 'react';
import { Camera } from 'expo';
import { Text, View, TouchableOpacity } from 'react-native';

export default class App extends React.Component {
    async press() {
        console.log('Button Pressed');
        if (this.camera) {
            console.log('Taking photo');
            let photo = await this.camera.takePictureAsync();
            console.log(photo);
        }
    }

    render() {
        return (
            <Camera
                style={{ flex: 1 }}
                ref={ (ref) => {this.camera = ref} }
            >
                <View style={{ flex: 1 }}></View>
                <TouchableOpacity
                    style={{ flex: 0, backgroundColor: 'red' }}
                    onPress={this.press}
                >
                    <Text>Touch Me</Text>
                </TouchableOpacity>
            </Camera>
        );
    }
}

发生的情况是:

  • 显示相机 View
  • press() 回调被调用,但没有拍照
  • 如果我删除 if (this.camera) 检查,我会收到警告,[未处理的 promise 拒绝:TypeError: undefined is not an object (evaluating 'this.camera.takePictureAsync ')]

在我看来,从未进行过对相机对象的引用,但我似乎无法弄清楚为什么会出现这种情况,或者我所做的与文档不同。

最佳答案

绑定(bind)press回调或使用箭头函数。

onPress={this.press} 替换为 onPress={this.press.bind(this)}

关于React-native refs 和 Expo Camera,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49229187/

相关文章:

javascript - 从 React Native 中的其他组件获取 'inherit' 的最佳方式?

css - 如何移除 React MUI Select 组件框架

javascript - 使用 redux 未定义值

reactjs - 当组件变大时如何拆分它。 ReactJs 或 React Native

react-native - 如何在没有 GPS 的情况下获取用户所在国家/地区

react-native - 如何在 React-Native 上设置第一个初始页面

react-native - 调用 onEndReached 时 React Native (Redux) FlatList 跳转到列表顶部

javascript - Expo React Native 仅加载自定义字体一次

ios - Expo AV 音频无法在 iOS/iPhone 上播放

node.js - 无法运行 npm install -g expo-cli