2017-02-18 49 views
0

我正在使用的項目有一個NotificationHeader組件,它具有顯示通知的基礎。具體來說,它有一個方法從子組件調用父組件的方法

addNotification(msg,type) { 
    console.log('addNotification.this:%O',this); 
    // rest of the method to show notification. 
} 

頁面上的其餘組件是這個NotificationHeader組件的子組件。我將addNotification方法作爲道具傳遞給兒童,以便我可以從他們那裏調用它。

我面臨的問題是,當我從子節點調用addNotification方法時,對addNotification的引用不是指向NotificationHeader組件,而是指向addNotification。

Image of the error in js console

,我已經看到了從調用子父組件的方法似乎不面對這個問題,其他的例子。

不得不提的是,由於該項目採用路由器作出反應,向下傳遞addNotification方法我使用React.cloneElement隨着孩子如下:

{React.cloneElement(this.props.children, { 
    addNotification: this.addNotification, 
})} 

我如何能得到這個參考NotificationHeader零件?

回答

1

我認爲你應該傳遞addNotification方法與綁定上下文。您可以使用bind做到這一點:

<SomeChildComponent addNotification={this.addNotification.bind(this)} /> 

,或者如果你克隆組件如你所提到的:

{React.cloneElement(this.props.children, { 
    addNotification: this.addNotification.bind(this) 
})} 
相關問題