TypeError: null is not an object (evaluating ''this.state.torchon')

TypeError: null is not an object (evaluating ''this.state.torchon')

我不知道下面的代码有什么问题...我想在相机拍摄期间切换闪光灯 on/off,但我的代码不起作用,我尝试将状态绑定到不同的方式,但仍然不适合我......下面是我的代码。我需要有关如何使其正常工作的帮助。

import React, { Component } from 'react';
import { View, StyleSheet, Text, TouchableOpacity } from 'react-native';
import { RNCamera } from 'react-native-camera';
import RNFetchBlob from 'rn-fetch-blob';
import Icon from 'react-native-vector-icons/Ionicons';

class cameraComponent extends Component {

    toggleTorch()
{
    let tstate = this.state.torchon;
    if (tstate == RNCamera.Constants.FlashMode.off){
       tstate = RNCamera.Constants.FlashMode.torch;
    } else {
       tstate = RNCamera.Constants.FlashMode.off;
    }
    this.setState({torchon:tstate})
}

    takePicture = async () => {
        if(this.camera) {
            const options = { quality: 0.5, base64: true };
            const data = await this.camera.takePictureAsync(options);
            console.log(data.base64)
            const path = `${RNFetchBlob.fs.dirs.CacheDir}/test.png`;
            console.log('path', path)
            try {
                RNFetchBlob.fs.writeFile(path, data.base64, 'base64')
            }
            catch(error) {
              console.log(error.message);
            }
        }
    };
  render() {
    return (
      <View style={styles.container}>
          <RNCamera
            ref = {ref=>{
                this.camera=ref;
            }}
            style={styles.preview}
            flashMode={this.state.torchon}
            // type = {RNCamera.Constants.Type.back}
            
          >

          </RNCamera>
          <View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center' }}>
              <TouchableOpacity onPress={this.takePicture.bind(this)} style={styles.captureBtn} />
          </View>

          <TouchableOpacity style={styles.toggleTorch}  onPress={this.toggleTorch.bind(this)}>
                { this.state.torchon == RNCamera.Constants.FlashMode.off? (
                        <Image style={styles.iconbutton} source={require('../images/flashOff.png')} />
                    ) : (
                        <Image style={styles.iconbutton} source={require('../images/flashOn.png')} />
                    )
                }
            </TouchableOpacity>


          
      </View>
    );
  };
}
export default cameraComponent;

您没有在任何地方初始化状态,当您访问 this.state.torchon 时它会抛出错误,因为 this.state 为空。 你必须初始化状态。

class cameraComponent extends Component {
    this.state={ torchon:RNCamera.Constants.FlashMode.off };
    toggleTorch=()=>
    {
      let tstate = this.state.torchon;
      if (tstate == RNCamera.Constants.FlashMode.off){
         tstate = RNCamera.Constants.FlashMode.torch;
      } else {
        tstate = RNCamera.Constants.FlashMode.off;
      }
      this.setState({torchon:tstate})
   }

您也可以在构造函数中初始化状态。