未定义不是一个对象(评估'state.cameraType')
问题描述:
我试图让一个React Native应用程序设置后面this后,然后移植到ES6。这里的主要网页代码:未定义不是一个对象(评估'state.cameraType')
"use strict";
import React, { Component } from 'react';
import Camera from 'react-native-camera';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
TouchableHighlight,
} from 'react-native';
export default class AwesomeProject extends Component {
constructor(props) {
super(props);
this.state = {cameraType: Camera.constants.Type.back};
}
render() {
return (
<Camera
ref="cam"
style={styles.container}
type={this.state.cameraType}>
<View style={styles.buttonBar}>
<TouchableHighlight style={styles.button} onPress={this._switchCamera.bind(this)}>
<Text style={styles.buttonText}>Flip</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.button} onPress={this._takePicture.bind(this)}>
<Text style={styles.buttonText}>Take</Text>
</TouchableHighlight>
</View>
</Camera>
);
}
_switchCamera:() => {
var state = this.state;
console.log(this.state);
state.cameraType = state.cameraType === Camera.constants.Type.back ? Camera.constants.Type.front : Camera.constants.Type.back;
this.setState(state);
}
_takePicture:() => {
console.log(this.refs);
this.refs.cam.capture(function(err, data) {
console.log(err, data);
});
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "transparent",
},
buttonBar: {
flexDirection: "row",
position: "absolute",
bottom: 25,
right: 0,
left: 0,
justifyContent: "center"
},
button: {
padding: 10,
color: "#FFFFFF",
borderWidth: 1,
borderColor: "#FFFFFF",
margin: 5
},
buttonText: {
color: "#FFFFFF"
}
});
AppRegistry.registerComponent('AwesomeProject',() => AwesomeProject);
我得到一个奇怪的错误说法都state.cameraType
是不确定的,this.refs
是不确定的。我有一种预感,有些东西没有被绑定,我的this
没有指向正确的东西,但我试过使用两个箭头函数和显式绑定。见下面的评论。无论如何,我不确定它为什么会表现出任何想法?
非常类似this post除了我已经尝试了两个建议的解决方案,所以我觉得其他东西缺失或我正在做绑定错误。
编辑:是否有理由被低估?我不清楚的东西:
答
事实证明,手动绑定是要走的路,只需要重新加载应用程序。我没有启用热插拔。或者,箭头功能也应该起作用。
另一件需要指出的事情是,对于iOS 10及更高版本,您必须在Info.plist
文件中设置2个东西,Privacy - Camera Usage Description
和Privacy - Photo Library Usage
。它可以是任何字符串值。