[英]React Native, setting value of item in state incorrectly
constructor(props) {
super(props);
this.state = {
message: "..",
};
}
render() {
return (
<View style={styles.container}>
<View style={styles.textInput}>
<TextInput onChangeText={(message) => this.setState({message})} placeholder="Enter your message..." style={styles.text}/>
<TouchableHighlight style={styles.button} onPress={this.submit}>
<Text ref="message" onPress={this.submit}>Submit</Text>
</TouchableHighlight>
</View>
</View>
)
}
loadData(){
AlertIOS.alert(this.state.message);
}
componentDidMount(){
this.loadData()
}
submit(){
AlertIOS.alert(this.state.message);
}
When loadData
is first called, it shows the current value of message: ".." 首次调用
loadData
,它将显示消息的当前值:“ ..”
When my submit
function is called, it throws an error: undefined is not an object (evaluating 'this.state.message')
当我
submit
函数被调用时,它抛出一个错误: undefined is not an object (evaluating 'this.state.message')
I'm assuming that it is my onChangeText attribute that's setting message to undefined, but I'm not sure why. 我假设是我的onChangeText属性将消息设置为undefined,但是我不确定为什么。
The problem is that this
isn't bound correctly in submit()
问题是,
this
在submit()
未正确绑定
In your constructor, try adding the line: 在构造函数中,尝试添加以下行:
this.submit = this.submit.bind(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.