【问题标题】:React-Native TypeError: undefined is not an object . (Please explain what this error means)React-Native TypeError: undefined is not an object 。 (请解释这个错误是什么意思)
【发布时间】:2020-06-16 14:17:25
【问题描述】:

我有一个名为 Cameraa 的组件类(Camera 中的额外 a 是有意的)。 创建组件类后,我在 App.js 中调用 render() 中的组件,但这会引发以下错误:

TypeError: undefined is not an object (evaluation '_reactNativeCamera.default.constants')。请有人可以解释一下我在这里做错了什么。

请注意: 1. 为 Android 开发 Reat-Native 2. 使用 react-native-camera 库

来自 App.js 的渲染方法

import React from 'react';
import { SafeAreaView,StyleSheet,ScrollView,TouchableOpacity,View,Text,Button, 
 StatusBar,FlatList} from 'react-native';


import email from 'react-native-email';
import Header from './components/Header.js';
import InputBar from './components/InputBar.js';
import TodoItem from './components/TodoItem.js';
import Cameraa from './components/Cameraa.js';

render()
 {


    return(

          <View style={styles.container}>




              <Header title="Todo App"/>
              <InputBar
                SendEmail={() => this.SendEmail()}
                addNewTodo={ () => this.addNewTodo()}
                textChange={todoInput =>
                this.setState({todoInput:todoInput})}
                todoInput={this.state.todoInput}

               />

               <Cameraa />

               <FlatList
                data= {this.state.todos}
                extraData={this.state}
                keyExtractor = {(item,index) => index.toString()}
                renderItem = { ({item,index}) =>{


                    return(
                        <TodoItem todoItem={item}
                        toggleDone={() =>this.toggleDone(item)}
                        sendEmail = {() => this.SendEmail(item)}
                         removeTodo = {() => this.removeTodo(item)}/>

                    )

                }}


               />




           </View>

    );

  }

相机类/组件

import React, {Component} from 'react';
import{
    StyleSheet,
    View,
    StatusBar,
    Dimensions,
    TouchableOpacity,
}from 'react-native';
import Camera from 'react-native-camera';




let{height,width} = Dimensions.get('window');
let orientation = height > width ? 'Portrait' : 'Landscape';


class Cameraa extends Component {
    constructor(props)
    {
        super(props);
        this.state={
            orientation
        };
    }

    componentWillMount(){
        Dimensions.addEventListener('change',this.handleOrientationChange);
    }

    componentWillUnmount(){
        Dimensions.removeEventListener('change', this.handleOrientationChange)
    }

    handleOrientationChange = dimensions => {
        ({height,width} = dimensions.window);
        orientation= height > width ? 'Portrait' : 'Landscape';
        this.setState({orientation});
    };

    takePicture() {
        this.camera
            .capture()
            .then(data => {
                console.log(data);
            })
            .catch(err=>{
                console.error('capture picture erro');
            });
    }

    render() {
        return(
            <View style={{flex: 1}}>
                <StatusBar barStyle="light-content" translucent/>

                <Cameraa
                     captureTarget = {Camera.constants.CaptureTarget.disk}
                     ref = {cam=>{
                         this.camera = cam;
                      }}
                        style={styles.cameraContainer}
                        aspect = {Camera.constants.Aspect.fill}
                        orientation = "auto"
                >
                <View
                   style={this.state.orientation=== 'Portrait' ?
                   (styles.buttonContainerPortrait):(styles.buttonContainerLandscape)}
                >
                <TouchableOpacity
                    onPress={() => this.takePicture()}
                    style={ this.state.orientation === 'Portrait' ? (styles.buttonPortrait)
                    :(styles.buttonContainerLandscape)}
                >
                    <Icon
                        name="close-circle"
                        style={{fontSize: 40, color:'white'}}
                    />
                </TouchableOpacity>
                </View>
                </Cameraa>
             </View>

        );


    }
 }

    const styles = StyleSheet.create({
        cameraContainer:{
            flex : 1
        },
        buttonContainerPortrait:{
            position: 'absolute',
            bottom: 0,
            left: 0,
            right: 0,
            flexDirection: 'row',
            justifyContent: 'center',
            backgroundColor: 'rgba(0,0,0,0.9)'
        },
        buttonContainerLandscape:{
            position: 'absolute',
            bottom:0,
            top:0,
            right:0,
            flexDirection: 'column',
            justifyContent: 'center',
            backgroundColor: 'rgba(0,0,0.5)'
        },
        buttonPortrait:{
            backgroundColor: 'transparent',
            padding: 5,
            marginHorizontal: 20
        },
        buttonContainerLandscape:{
            backgroundColor: 'transparent',
            padding: 5,
            marginVertical: 20

        }


    });

    export default Cameraa;

【问题讨论】:

  • 试试这个代码Camera.RNCamera.constants

标签: android react-native


【解决方案1】:

Constants 中的C 需要大写,即Camera.Constants.Type.back

这个错误只是告诉你Camera.constants 不存在,它不存在:)

【讨论】:

    【解决方案2】:

    根据react-native-camera的官方文档,你只需要import { RNCamera } from 'react-native-camera'模块,然后使用&lt;RNCamera/&gt;标签。

    Camera.constants 导致错误,我不知道为什么!

    但最近我使用了RNCamera,它工作正常。

    import React, { Component } from 'react';
    import {View,Text, TouchableOpacity} from 'react-native';
    import styles from "./styles"; //external stylesheet for this page
    import { RNCamera } from 'react-native-camera';
    export default class CameraComp extends Component {
        constructor(){
            super();
            this.state={
                file:''
            }
        }
        render() {
            return (
                <View style={styles.container}>
                    <RNCamera
                        ref={ref => { this.camera = ref; }}
                        style={styles.preview}
                        type={RNCamera.Constants.Type.back}
                        flashMode={RNCamera.Constants.FlashMode.on}
                        androidCameraPermissionOptions={{ title: 'Permission to use camera', message: 'We need your permission to use your camera', buttonPositive: 'Ok', buttonNegative: 'Cancel',}}
                        androidRecordAudioPermissionOptions={{ title: 'Permission to use audio recording', message: 'We need your permission to use your audio', buttonPositive: 'Ok', buttonNegative: 'Cancel', }}
                        onGoogleVisionBarcodesDetected={({ barcodes }) => {
                            console.log(barcodes);
                        }}
                    />
                    <View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center' }}>
                    <TouchableOpacity onPress={this.takePicture.bind(this)} style={styles.capture}>
                        <Text style={{ fontSize: 14 }}> SNAP </Text>
                    </TouchableOpacity>
                    </View>
                </View>
            );
        }
        takePicture = async() => {
            if (this.camera) {
                const options = { quality: 0.5, base64: true };
                const data = await this.camera.takePictureAsync(options);
                console.log(data.uri);
            }
        };
    }
    

    【讨论】:

    • 谢谢@Karishma。出于某种原因,当我最初尝试 react-native-camera 文档中的代码时,它抛出了一些错误。所以我选择了一个不同的例子。但它现在正在工作。
    • 不客气@user1462617,因为你已经接受了我的回答,你也可以投票吗!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2020-08-31
    相关资源
    最近更新 更多