正如您在下面的两个组件中看到的,我想从面板组件中的按钮单击中删除配方(在应用程序组件中), 我有一个方法在应用程序中删除配方,并支持(onclick)发送到子panelcomponent。 Panel然后从配方地图中获取索引,并在按钮单击后执行handleDelet方法将索引发送回父级。但不,这不起作用!
class App extends React.Component {
state={
addRecipe:{recipeName:"",ingredients:[]},
recipes:[{recipeName:"Apple",ingredients:["apple","onion","spice"]},
{recipeName:"Apple",ingredients:["apple","onion","spice"]},
{recipeName:"Apple",ingredients:["apple","onion","spice"]}]
}
handleDelete = (index) => {
let recipes = this.state.recipes.slice();
recipes.splice(index,1); //deleting the index value from recipe
this.setState({recipes}) //setting the state to new value
console.log(index,recipes)
}
render() {
return (
<div className="container">
<PanelComponent recipes={this.state.recipes} onClick={()=>this.handleDelete(index)}/>
<ModalComponent />
</div>
);
}
}
class PanelComponent extends React.Component {
handleDelete = (index) => {
this.props.onClick(index); //sending index to parent after click
console.log(index)
}
render() {
return (
<PanelGroup accordion>
{this.props.recipes.map( (recipe,index) => {
return(
<Panel eventKey={index} key={index}>
<Panel.Heading>
<Panel.Title toggle>{recipe.recipeName}</Panel.Title>
</Panel.Heading>
<Panel.Body collapsible>
<ListGroup>
{recipe.ingredients.map((ingredient)=>{
return(<ListGroupItem>{ingredient}</ListGroupItem>);
})}
</ListGroup>
<Button bsStyle="danger" onClick={()=>this.handleDelete(index)}>Delete</Button>
<EditModalComponent />
</Panel.Body>
</Panel>
);
})}
</PanelGroup>
);
}
}
答案 0 :(得分:2)
你的代码中的实际错误是,在onClick in parent中使用arrow函数时,你传递的是错误的参数,而不是{()=>this.handleDelete(index)}
你应该写的是
{(value)=>this.handleDelete(value)}
,但是,这也没有必要,你可以简单地在App中编写{this.handleDelete}
,因为你的handleDelete函数已经绑定并且它从Child组件接收了值。
render() {
return (
<div className="container">
<PanelComponent recipes={this.state.recipes} onClick={(value)=>this.handleDelete(value)}/>
<ModalComponent />
</div>
);
}
写{()=>this.handleDelete(index)}
与{(value)=>this.handleDelete(value)}
的区别在于,在第一种情况下,您显式传递从App组件中的map函数获得的索引,而在第二种情况下,值当您执行this.props.onClick(value)
函数时,从子组件传递到handleDelete
函数。
答案 1 :(得分:1)
你错误地将这个功能作为道具发送。您将函数的结果作为道具而不是函数本身发送
class App extends React.Component {
state={
addRecipe:{recipeName:"",ingredients:[]},
recipes:[{recipeName:"Apple",ingredients:["apple","onion","spice"]},
{recipeName:"Apple",ingredients:["apple","onion","spice"]},
{recipeName:"Apple",ingredients:["apple","onion","spice"]}]
}
handleDelete = (index) => {
let recipes = this.state.recipes.slice();
recipes.splice(index,1); //deleting the index value from recipe
this.setState({recipes}) //setting the state to new value
console.log(index,recipes)
}
render() {
return (
<div className="container">
//change here
<PanelComponent recipes={this.state.recipes} onClick={this.handleDelete}/>
<ModalComponent />
</div>
);
}
}