[英]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.