2017-04-06 63 views
3

如何在該組件函數中獲取React組件狀態。這沒有與狀態相關的對象。我得到這個。狀態未定義在板removeComment函數。基本上在董事會removeComment函數我想刪除該索引的評論元素(作爲參數傳遞)。無法訪問事件處理程序函數中的`this.state`:ReactJS

class Board extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      comments:[ 
      "One", 
      "Two", 
      "Three", 
      "four", 
      "five" 
     ]}; 
    }; 
    removeComment(index) { 
     console.log('i was called',this.state); 
    } 
    render() { 
     console.log(this.state); 
     return (
      <div className="board"> 
       { 
        this.state.comments.map((text,i) => { 
         return (
          <Comment key ={i} index = {i} commentText={text} removeComment={this.removeComment}/> 
         ) 
        }) 
       } 
      </div> 
     ); 
    } 
} 

class Comment extends React.Component { 
    removeComment() { 
    var index = this.props.index; 
    this.props.removeComment(index); 
    } 
    render() { 
    return(
     <div onClick={this.removeComment.bind(this)}>{this.props.commentText}</div> 
    ); 
    } 
} 

回答

3

因爲你忘了該方法removeComment綁定在Board組件,使用這條線:

removeComment={this.removeComment.bind(this)} 

使用這Board組件:

<div className="board"> 
    { 
     this.state.comments.map((text,i) => { 
      return (
       <Comment key ={i} index = {i} commentText={text} removeComment={this.removeComment.bind(this)}/> 
      ) 
     }) 
    } 
</div> 
+0

感謝花花公子。你拯救了我的一天。 –

+0

很高興,幫助你:) –

相關問題