【问题标题】:How do I expand multiple cards in react with state?如何扩展多张卡片以响应状态?
【发布时间】:2022-01-28 01:39:53
【问题描述】:

我有一张卡片清单。单击每张卡片后,我希望它们扩展更多信息。我从服务器获取卡片并映射它们。为了扩展单张卡而不是多张卡,我创建了一个状态 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;

【问题讨论】:

  • 另一个简单的解决方案是创建一个单独的组件(例如StudentCard)来呈现单个学生卡。然后,您可以在每张学生卡中设置一个状态(打开/关闭)。

标签: javascript reactjs react-hooks tailwind-css


【解决方案1】:

在扩展卡的id 值中,有一个Set,而不是editIndex

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

【讨论】:

    【解决方案2】:

    尝试使用扩展卡的数组或映射:

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

    【讨论】:

      【解决方案3】:

      您应该用一个对象声明并在该对象中保留扩展的卡片 ID。使用对象而不是数组可以避免循环过滤数组

        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 Design 库的 Collapse 组件。所以留下崩溃问题吧。

      https://ant.design/components/collapse/

      和其他复杂的组件在库中可用的应该检查一下。

      【讨论】:

        猜你喜欢
        • 2020-03-16
        • 2023-02-12
        • 2021-09-22
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        • 2018-03-18
        • 2019-04-17
        • 1970-01-01
        相关资源
        最近更新 更多