[英]How do I expand multiple cards in react with state?
我有一张卡片清单。 单击每张卡片后,我希望它们扩展更多信息。 我从服务器和 map 获得卡。 为了扩展单张卡,而不是多张卡,我创建了一个 state 编辑索引,它检查卡的 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;
而不是editIndex
,有一Set
扩展卡的id
值:
const [editing, setEditing] = useState(new Set());
然后,扩展/收缩卡片(遗憾的是, 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;
});
};
要确定卡片是否展开,它是editing.has(id)
:
{editing.has(id) && (
<div>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
</div>
)}
尝试使用扩展卡的阵列或 map:
const [editIndex, setEditIndex] = useState([]);
...
const handleExpand = (id) => {
setEditIndex((e) => (e.includes(id) ? e.filter(i => i !== id) : [...e, id]))
};
...
{editIndex.includes(id) && (
<div>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
</div>
)}
您应该使用 state 和 object 并将扩展卡 ID 保留在 object 中。 使用 object 代替数组可以避免循环过滤数组
import React, { useState } from 'react';
function Card() {
const [studentList, setStudentList] = useState();
const [editIndex, setEditIndex] = useState({});
const handleExpand = (id) => {
setEditIndex((e) => (e === id ? null : id))
setEditIndex({id: !editIndex[id]});
};
return studentList.map((student, index) =>
<div onClick={() => handleExpand(index)} className={`otherClassNames ${editIndex[index]?"expanded":"collapsed"}`}>
{JSON.stringify(student)} // render student data
</div>
);
}
export default Card;
另一方面,您可以使用 Ant 设计库的 Collapse 组件。 所以留下崩溃问题他们。
https://ant.design/components/collapse/
库中可用的其他复杂组件应检查出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.