gpt4 book ai didi

reactjs - Props 父组件到父子组件

转载 作者:行者123 更新时间:2023-12-03 14:26:19 33 4
gpt4 key购买 nike

如何从子组件(Card)调用父组件(App)中的函数?

卡片组件渲染一项(CHILD)

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>
);
}
}

说明

我想删除状态列表中的项目,但该列表位于父组件中,我该怎么做?

最佳答案

您可以将 deleteCard 方法作为 prop 传递给 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>

关于reactjs - Props 父组件到父子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53226241/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com