React JS Animated手风琴-使用详细信息和摘要构建

时间:2020-09-14 15:51:09

标签: javascript css reactjs

我目前正在使用<details /><summary />在React中构建自定义手风琴 这是我到目前为止的内容-codesandbox

正如在codesandbox中看到的那样,正在发生一个奇怪的问题。每次我单击其中一个手风琴时,仅显示最后一项的内容。我不知道是什么引起了奇怪的问题。

我的手柄点击功能的代码段,有关完整代码,请参见上面的沙盒链接:

  const handleClick = (e) => {
    e.preventDefault();

    const accordion = summaryRef.current.parentNode;
    const content = contentRef.current;

    if (accordion.hasAttribute("open")) {
      content.style.removeProperty("max-height");
      content.classList.add("closed");
      setTimeout(() => {
        accordion.removeAttribute("open");
      }, 400);
      return;
    }
    // If the <details> element is closed, add the [open] attribute (so the content will render), and animate in
    accordion.setAttribute("open", "");
    // Get proper max-height for element for better animation
    if (!content.getAttribute("data-height")) {
      content.style.maxHeight = "none";
      content.setAttribute(
        "data-height",
        `${content.getBoundingClientRect().height}px`
      );
      content.style.removeProperty("max-height");
    }
    // Wait for the browser to apply [open] to <details>, then animate
    setTimeout(() => {
      content.classList.remove("closed");
      content.style.maxHeight = content.getAttribute("data-height");
    }, 0);
  };

任何帮助/建议将不胜感激!

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为您在summaryRef循环中重新引用了contentReffor。因为那ref的实际价值将是最后一项。我建议将项目作为单独的组件制造,并在其下保留引用。