【问题标题】:React-native refs and Expo CameraReact-native refs 和 Expo Camera
【发布时间】:2018-08-20 02:47:42
【问题描述】:

我正在尝试使用 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>
        );
    }
}

会发生什么:

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

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

【问题讨论】:

    标签: react-native expo


    【解决方案1】:

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

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

    【讨论】:

    • 类方法默认不绑定。如果需要引用不带 () 的方法,例如 onPress ={this.press},则应绑定该方法以保留上下文。或者你可以使用箭头函数,但这意味着每次都会创建一个新的匿名函数。 react docs
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多