【发布时间】:2018-01-19 06:24:14
【问题描述】:
正如您在下面的两个组件中看到的那样,我想通过单击面板组件中的按钮来删除食谱(在应用程序组件中), 我在应用程序中有一个删除配方的方法,并将一个 prop(onclick) 发送到子面板组件。 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>
);
}
}
【问题讨论】:
-
我认为你错误地将函数作为道具发送,试试这个
否则你正在sneding函数的结果作为道具而不是函数本身 -
@Sujit.Warrier 能否编辑并显示给我看。谢谢
-
@Sujit.Warrier 点击不更新后我现在正在获取索引值
-
索引值在parent还是child?
-
@Sujit.Warrier 现在可以使用了,谢谢
标签: javascript reactjs