如何从子组件(卡)调用父组件(应用)中的函数?
卡片组件呈现一项(儿童)
const Card = (props) => {
return (
<div style={{margin: '1em'}}>
<img alt="Profile" width="75" src={props.avatar_url} />
<div style={{display: 'inline-block', marginLeft: 10}}>
<div style={{fontSize: '1.25em', fontWeight: 'bold'}}>
{props.name}
</div>
<div>{props.company}</div>
<button
//when I click here should trigger App's delete func who deletes the select item.
onClick = { () => alert()}
className="btn btn-danger btn-sm">Delete</button>
</div>
</div>
);
};
CardList组件呈现项目列表( CHILD-PARENT )
const CardList = (props) => {
return (
//Props.nameProp = Value {...Card} spred operator
<div>
{props.cards.map(card => <Card key={card.id} {...card} />)}
</div>
);
}
父组件:
class App extends React.Component {
state = {
cards: [
]
};
addNewCard = (cardInfo) => {
this.setState(prevState => ({
cards: prevState.cards.concat(cardInfo)
}))
};
deleteCard = (selectedCard) => {
this.setState(prevState => ({
//array.filter creates a new array with elements who pass the foo
cards: prevState.cards.filter(card => card !== selectedCard)
}));
}
render(){
const {
cards,
} = this.state;
return(
<div className="container" style={{marginTop: 15}}>
<Form onSubmit={this.addNewCard} />
<div className="container" style={{padding: 20}}>
{
cards.length > 0 ?
<CardList cards={cards} />
:
<p>Your list is empty</p>
}
</div>
</div>
);
}
}
EXPLANATION
我要删除状态列表中但该列表位于父组件中的项目,我该怎么做?
答案 0 :(得分:1)
您可以将deleteCard
方法作为对CardList
的支持,并从CardList
传递到每个Card
组件,然后在其中调用。
示例
const Card = props => (
<button onClick={() => props.deleteCard(props.card)}>{props.card}</button>
);
const CardList = props => (
<div>
{props.cards.map(card => (
<Card card={card} deleteCard={props.deleteCard} />
))}
</div>
);
class App extends React.Component {
state = {
cards: [1, 2, 3]
};
deleteCard = card => {
this.setState(({ cards }) => ({
cards: cards.filter(element => element !== card)
}));
};
render() {
const { cards } = this.state;
return <CardList cards={cards} deleteCard={this.deleteCard} />;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>