[英]Value not getting passed from child to parent component in React
正如您在下面的两个组件中所看到的,我想从面板组件中的按钮单击中删除配方(在应用程序组件中),我在app中有一个方法可以删除配方,并且一个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>
);
}
}
您的代码中的实际错误是,在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)}
vs {(value)=>this.handleDelete(value)}
在于,在第一种情况下,您显式传递从map函数获得的索引在您的App组件中,在第二种情况下,执行this.props.onClick(value)
时从子组件传递的this.props.onClick(value)
将提供给handleDelete
函数。
你错误地发送功能作为道具。 您将函数的结果作为props而不是函数本身发送
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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.