Undefined 不是 this.state 中的对象 - ReactNative [英] Undefined is not a object in this.state - ReactNative
本文介绍了Undefined 不是 this.state 中的对象 - ReactNative的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 ReactNative
的新手,我在我的 this.state.rows
中收到错误 undefined is not a object
我我试图在用户单击 Button
时动态添加 View
.我尝试使用 this 而不是使用getInitialState
我使用了 constructor(props)
但我一直有上述错误.这是我的代码
I'm new in ReactNative
, I'm getting the error undefined is not a object
in my this.state.rows
I am trying to dynamically add a View
when a user clicks a Button
. I tried using this and instead of using getInitialState
I used constructor(props)
but I keep on having the said error. Here is my code
constructor(props) {
super(props);
this.state = {
rows: [],
};
}
addRow(){
this.state.rows.push(index++)
this.setState({ rows: this.state.rows })
}
render(){
let contactView = () => {
return <View>
<AddComponent />
</View>
}
return(
<View>
<View>
{contactView}
</View>
<TouchableHighlight onPress={ this.addRow } >
<Text>Add</Text>
</TouchableHighlight>
</View>
);
感谢您的帮助!
推荐答案
你需要像这样将 this
绑定到函数 addRow:
You need to bind this
to the function addRow like this:
<TouchableHighlight onPress={ this.addRow.bind(this) } >
<Text>Add</Text>
</TouchableHighlight>
或者创建一个匿名函数来自动绑定这个:
or create an anonymous function to automatically bind this:
<TouchableHighlight onPress={ () => this.addRow() } >
<Text>Add</Text>
</TouchableHighlight>
有关解释,请参阅this.
这篇关于Undefined 不是 this.state 中的对象 - ReactNative的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文