我只是在尝试该状态变量为false,但我一直在收到错误消息
TypeError: undefined is not an object (evaluating '_this.state = {
showAddress: false
}')
我已经在互联网上寻求答案,而这个错误在一般术语中似乎很普遍。我尝试将其绑定到该功能,但我似乎没有什么可以更改该错误消息。
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, TouchableHighlight, Alert} from 'react-native';
export default class PickupLocation extends React.Component {
constructor() {
this.state = {
showAddress: false
};
/* this.submitAddress = this.submitAddress.bind(this);
this.renderSubmitAddress = this.renderSubmitAddress.bind(this);*/
}
submitAddress = () => {
this.setState({
showAddress: !this.state.showAddress
})
}
renderSubmitAddress = () => {
if(this.state.showAddress){
return (
<View><Text>Jason Was Here</Text></View>
)
} else {
return null;
};
}
render() {
return (
<View style={styles.textArea} >
<View>
<TextInput
style={{height: 40, borderColor: 'gray', backgroundColor: 'white', borderWidth: 1}}
onChangeText={(text) => this.setState({text})}
placeholder="What is your pickup point?"
placeholderTextColor='grey'
onSubmitEditing={this.submitAddress()}
/>
{this.renderSubmitAddress()}
<View style={styles.Button} >
<TouchableHighlight buttonStyle={styles.Button} title="Press Me"
onPress={() => {Alert.alert("jason is testing");}} >
<Text style={styles.submitText}>Submit Pickup Location</Text>
</TouchableHighlight>
</View>
</View>
</View>
)
}
}
我最喜欢在这个问题上副本,但是我尝试了我在这里可以找到的一切,但似乎没有任何答案改变任何东西。
事先感谢您的任何帮助。
您需要在构造函数中调用super()
。
constructor() {
super();
this.state = {
showAddress: false
};
}
此外,还有其他几个应该修复的项目。
当您在setState
调用中访问当前状态时,您应该使用将函数作为参数的版本,例如:
submitAddress = () => {
this.setState((prevState) => ({
showAddress: !prevState.showAddress
}))
}
另外,您要经过的处理程序应修改:
onSubmitEditing={this.submitAddress.bind(this)}