import React, { Component } from "react";
import FriendCard from "./components/FriendCard";
import Wrapper from "./components/Wrapper";
import Title from "./components/Title";
import friends from "./friends.json";
import "./App.css";
class App extends Component {
// Setting this.state.friends to the friends json array
state = {
friends
};
removeFriend = id => {
// Filter this.state.friends for friends with an id not equal to the id being removed
const friends = this.state.friends.filter(friend => friend.id !== id);
// Set this.state.friends equal to the new friends array
this.setState({ friends });
};
// Map over this.state.friends and render a FriendCard component for each friend object
render() {
return (
<Wrapper>
<Title>Friends List</Title>
{this.state.friends.map(friend => (
<FriendCard
removeFriend={this.removeFriend}
id={friend.id}
key={friend.id}
name={friend.name}
image={friend.image}
occupation={friend.occupation}
location={friend.location}
/>
))}
</Wrapper>
);
}
}
export default App;
下面的代码片段允许我单击card
(bootstrap-css) 并删除card
。有用!但我的逻辑思维或方法是点击删除这张卡
。我在这段代码中没有看到这一点,但它有效。我没有编程背景。
如果您认为的话,我希望有人可以向我解释它并用外行术语理解它。也许还可以引导我举几个例子。提前致谢。
removeFriend = id => {
const friends = this.state.friends.filter(friend => friend.id !==
id);
this.setState({ friends });
};
整体如下:
这是 friend 组件:
import React from "react";
import "./FriendCard.css";
const FriendCard = props => (
<div className="card">
<div className="img-container">
<img alt={props.name} src={props.image} />
</div>
<div className="content">
<ul>
<li>
<strong>Name:</strong> {props.name}
</li>
<li>
<strong>Occupation:</strong> {props.occupation}
</li>
<li>
<strong>Location:</strong> {props.location}
</li>
</ul>
</div>
<span onClick={() => props.removeFriend(props.id)} className="remove">
𝘅
</span>
</div>
);
export default FriendCard;
最佳答案
所以您在此处发布的部分
removeFriend = id => {
const friends = this.state.friends.filter(friend => friend.id !== id);
this.setState({ friends });
};
这是你的逻辑思维的最后一部分删除这张卡
这是在单击时调用的函数,但不处理实际的单击。 它将 id 作为输入,并将您的 friend 状态设置为与给定 id 匹配的所有元素。 这是通过过滤器函数完成的,您可以在此处阅读更多信息 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
您的逻辑思维的下一部分点击在 FriendCard 组件中处理
在您的 App 组件中,此行将您的处理函数作为属性注入(inject) FriendsCard 组件中
removeFriends={this.removeFriends}
这意味着只要单击 FriendCard 组件,您的removeFriends 函数就会被调用。
实际的点击处理是在这一行的 FriendCard 组件中完成的
<span onClick={() => props.removeFriend(props.id)} className="remove">
关于javascript - 解释如何在 REACT 中删除引导卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49075527/