3st*_*cks 1 javascript reactjs tailwind-css react-hooks
我有一张卡片清单。单击每张卡片后,我希望它们能够展开并提供更多信息。我从服务器获取卡片并绘制它们。为了扩展单张卡而不是多张卡,我创建了一个状态 editIndex,它检查卡的 id,以便它可以正常工作并专门扩展该卡。我不知道如何同时扩展一张卡和另一张卡。因为现在如果我点击卡片,另一张展开的卡片就会折叠起来。
const [studentList, setStudentList] = useState();
const [input, setInput] = useState(" ");
const [editIndex, setEditIndex] = useState(null);
const [suggestions, setSuggestions] = useState(null);
const handleExpand = (id) => {
setEditIndex((e) => (e === id ? null : id))};
return (
<div
className="flex
flex-col
w-4/5
h-[800px]
overflow-scroll
scrollbar-hide
border
bg-white
rounded-xl
"
>
<div>
{studentList?.map(
({
city,
company,
email,
firstName,
grades,
id,
lastName,
pic,
skill,
}) => (
<div
key={uuidv4()}
onClick={(e) => handleExpand(id)}
className="flex border-b-2 py-2 px-7 xl:px-12 cursor-pointer
mb-2 max-h-96 transition transform ease duration-200;
"
>
<div className="flex items-center ">
<img
src={pic}
className="flex items-center border rounded-full object-cover w- [100px] h-[100px]"
/>
</div>
<div className="ml-10 superTest ">
<p className="font-bold text-4xl">
{firstName} {lastName}
</p>
<p>E-mail: {email}</p>
<p>Company: {company}</p>
<p>Skill: {skill}</p>
<p>Average: {grades}% </p>
{editIndex === id && (
<div>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
</div>
)}
</div>
</div>
)
)}
</div>
</div>
);
}
export default Card;
Run Code Online (Sandbox Code Playgroud)
取而代之的editIndex是扩展卡的值Set:id
const [editing, setEditing] = useState(new Set());
Run Code Online (Sandbox Code Playgroud)
然后,扩展/收缩一张卡(遗憾的是,Set没有内置toggle方法):
const handleExpand = (id) => {
setEditing(editing => {
// Copy the set
editing = new Set(editing);
if (editing.has(id)) {
// Already editing, stop editing
editing.delete(id);
} else {
// Not editing, start
editing.add(id);
}
return editing;
});
};
Run Code Online (Sandbox Code Playgroud)
要确定卡是否已扩展,请执行以下操作editing.has(id):
{editing.has(id) && (
<div>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
</div>
)}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1435 次 |
| 最近记录: |