2016-10-03 96 views
1

當我運行onEditNoteClick功能,我回來,說陣營的onClick函數參數返回undefined

Cannot read property 'onEditNoteClick' of undefined 

我不知道爲什麼我得到這個問題的錯誤。爲了使它更簡單,我將onEditNoteClick參數設置爲1,但它仍然不起作用。

constructor(props) { 
     super(props); 
     this.onEditNoteClick = this.onEditNoteClick.bind(this); 
    } 

    ...... 

    onEditNoteClick(id){ 
    console.log("came to this function"); 
    } 

    renderNotes(note) { 
    return (
     <tr key={note.id}> 
      <td> {note.name}</td> 
      <td> {note.description} </td> 
      <td className="edit" onClick={this.onEditNoteClick.bind(this,1)}><i className="fa fa-fw fa-pencil fa-lg"></i> </td> 
     </tr> 
    ); 
    } 

..... 

render(){ 
    {this.props.notes.map(this.renderNotes)} 

我想我需要添加一個綁定方法與注意事項地圖,是這樣的:

{this.props.notes.map(this.renderNotes).bind(this)} 

但我不知道正確的語法是什麼。

回答

2

我想我需要添加一個綁定方法與注意事項地圖,是這樣的:

{this.props.notes.map(this.renderNotes).bind(this)} 

這是不正確的。 .bind只能在函數上調用,但.map返回數組,而不是函數。您必須設置this.renderNotes方法的this值。實現這一目標最簡單的方法是通過this作爲第二個參數.map(見documentation):

{this.props.notes.map(this.renderNotes, this)} 

另外,結合this.renderNotesconstructor就像你用另一種方法做:

this.renderNotes = this.renderNotes.bind(this); 

然後你就可以忽略第二個參數:

{this.props.notes.map(this.renderNotes)} 

另請參閱:How to access the correct `this` context inside a callback?

+0

啊我明白了,這是有道理的。謝謝! – lost9123193