首页 > 解决方案 > 想要创建一个可折叠的列表

问题描述

我想从 JSON 数据创建一个 ul li 展开/折叠列表。JSON 数据是具有子父关系的嵌套 JSON 数据。我正在使用 babel TSX 页面来创建它。已经搜索了很多示例,但找不到最适合我的示例。请帮我。我是反应js的新手。这是我的 JSON 数据。

const nodes = [
{
value: "/app",
label: "app",
children: [
  {
    value: "/app/Http",
    label: "Http",
    children: [
      {
        value: "/app/Http/Controllers",
        label: "Controllers",
        children: [
          {
            value: "/app/Http/Controllers/WelcomeController.js",
            label: "WelcomeController.js",
          },
        ],
      },
      {
        value: "/app/Http/routes.js",
        label: "routes.js",
      },
    ],
  },
  {
    value: "/app/Providers",
    label: "Providers",
    children: [
      {
        value: "/app/Http/Providers/EventServiceProvider.js",
        label: "EventServiceProvider.js",
      },
    ],
  },
],
},
{
value: "/config",
label: "config",
children: [
  {
    value: "/config/app.js",
    label: "app.js",
  },
  {
    value: "/config/database.js",
    label: "database.js",
  },
],
 },
 {
value: "/public",
label: "public",
children: [
  {
    value: "/public/assets/",
    label: "assets",
    children: [
      {
        value: "/public/assets/style.css",
        label: "style.css",
      },
    ],
  },
  {
    value: "/public/index.html",
    label: "index.html",
  },
],
},
{
value: "/.env",
label: ".env",
 },
{
 value: "/.gitignore",
label: ".gitignore",
},
{
 value: "/README.md",
  label: "README.md",
 },
];

标签: reactjsbabeljs

解决方案


这是我自己写的一个简单的折叠组件:

import React, { useRef, useEffect } from "react";
import "./style.css";

const Collapse = ({ open, children }) => {
  const ref = useRef();
  useEffect(() => {
    let mounted = true;
    if (ref.current && open !== null && mounted) {
      if (open) ref.current.style.height = ref.current.scrollHeight + "px";
      else ref.current.style.height = "0px";
    }

    return () => {
      mounted = false;
    };
  }, [open]);

  return (
    <div className="c-collapse" ref={ref}>
      {children}
    </div>
  );
};

export default Collapse;

这是style.css

.c-collapse {
  height: 0;
  overflow: hidden;
  transition: height .3s ease-out;
  -webkit-transition: height .3s ease-out;
  -moz-transition: height .3s ease-out;
  -ms-transition: height .3s ease-out;
  -o-transition: height .3s ease-out;
}

现在你可以像这样使用它:

const [open, setOpen] = useState(false);

return (
    <>
        <button onClick={() => setOpen(state => !state)}>toggle</button>
        <Collapse open={open}>
            this is collapsable content
        </Collapse>
    </>
);

推荐阅读