reactjs - 想要创建一个可折叠的列表
问题描述
我想从 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",
},
];
解决方案
这是我自己写的一个简单的折叠组件:
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>
</>
);
推荐阅读
- html - 如何让验证器允许空白?
- php - 基于选择选项值的循环形式
- jquery - Datetimepicker 渲染不正确
- node.js - Socket.io 有时只发出事件
- python - 从一个文件中读取一个 IP 地址,然后在另一个文件中查找该 IP 并打印出对应的接口
- css - 如何设置工具提示的样式?
- python - 如何修复 pyxel 中的“无法在‘系统’中初始化 SDL”
- python - 使用带有 python 的 imagemagick 合成多组图像时的线程延迟
- protractor - 如何从 Protractor 中的 span 样式中获取文本?
- javascript - 打字稿抱怨接口中不存在私有属性