-1
我試圖讓一個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除了我已經嘗試了兩個建議的解決方案,所以我覺得其他東西缺失或我正在做綁定錯誤。
編輯:是否有理由被低估?我不清楚的東西: