簡體   English   中英

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

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

我是ReactNative ,我得到錯誤undefined is not a object我的this.state.rows undefined is not a object我試圖在用戶單擊Button時動態添加View 我嘗試使用這個而不是使用getInitialState我使用了constructor(props)但我繼續有上述錯誤。 這是我的代碼

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是這樣的:

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

或者創建一個匿名函數來自動綁定它:

<TouchableHighlight onPress={ () => this.addRow() } >
  <Text>Add</Text>
</TouchableHighlight>

有關解釋,請參閱此處

你也可以這樣做。

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);
    }
}

要調用該函數,您可以像這樣調用它。

<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