简体   繁体   English

Undefined不是this.state中的对象 - ReactNative

[英]Undefined is not a object in this.state - ReactNative

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 . 我是ReactNative ,我得到错误undefined is not a object我的this.state.rows undefined is not a object我试图在用户单击Button时动态添加View I tried using this and instead of using getInitialState I used constructor(props) but I keep on having the said error. 我尝试使用这个而不是使用getInitialState我使用了constructor(props)但我继续有上述错误。 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>
);

Thank you for your help! 谢谢您的帮助!

You need to bind this to the function addRow like this: 您需要绑定this的功能addRow是这样的:

<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>

For explanation refer to this . 有关解释,请参阅此处

You can do this too. 你也可以这样做。

export default class CustomCard extends React.Component{
    constructor(props) {
        super(props);

        // This binding is necessary to make `this` work in the callback
        this.functionName= this.handleUpvote.bind(this);
    }
}

For calling the function you can call it like this. 要调用该函数,您可以像这样调用它。

<TouchableHighlight onPress={this.functionName} >
  <Text>Add</Text>
</TouchableHighlight>
<TouchableHighlight onPress={ this.addRow.bind(this) } >
  <Text>some text</Text>
</TouchableHighlight>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM