2016-11-18 27 views
0

我需要將父函數傳遞給子組件,但由於該組件是在地圖函數中生成的,因此它似乎不起作用。以下是有問題的代碼:ReactJS將父函數傳遞給使用地圖創建的子代

{this.state.recipes.map(function(a,index){ 
    return (<Recipe name={a.name} ingredients={a.ingredients} index={index} onClick={this.handleDelete}/>); 
} 

解決此問題的最佳方法是什麼?

回答

2

無論它是否在地圖功能中生成組件都沒關係。我認爲你只是忘了綁定你的功能。

您的代碼應該是這樣的

{this.state.recipes.map(function(a,index){ 
    return (<Recipe name={a.name} ingredients={a.ingredients} index={index} onClick={this.handleDelete.bind(this}/>); 
} 

您也可以使用方向的功能,如:

{this.state.recipes.map((a,index) => <Recipe name={a.name} ingredients={a.ingredients} index={index} onClick={this.handleDelete.bind(this}/>)} 

這裏是jsfiddle