ReactJS 将父函数传递给使用 map 创建的子函数
ReactJS passing parent function into child created using map
我需要将父函数传递给子组件,但由于组件是在映射函数中创建的,所以它似乎不起作用。这是有问题的代码:
{this.state.recipes.map(function(a,index){
return (<Recipe name={a.name} ingredients={a.ingredients} index={index} onClick={this.handleDelete}/>);
}
解决这个问题的最佳方法是什么?
它的组件是否在地图功能中制作并不重要。我想你只是忘了绑定你的函数。
你的代码应该是这样的
{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。
我需要将父函数传递给子组件,但由于组件是在映射函数中创建的,所以它似乎不起作用。这是有问题的代码:
{this.state.recipes.map(function(a,index){
return (<Recipe name={a.name} ingredients={a.ingredients} index={index} onClick={this.handleDelete}/>);
}
解决这个问题的最佳方法是什么?
它的组件是否在地图功能中制作并不重要。我想你只是忘了绑定你的函数。
你的代码应该是这样的
{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。