Tree 树形组件封装

整体思路

  1. 数据结构设计

    • 使用递归的数据结构(TreeNode)表示树形数据
    • 每个节点包含idname、可选的children数组和selected状态
  2. 状态管理

    • 使用useState在组件内部维护树状态的副本
    • 通过deepCopyTreeData函数进行深拷贝,避免直接修改原始数据
  3. 核心功能实现

    • checkChildrenStatus:检查子节点状态,用于确定父节点的选中状态
    • updateNodeStatus:递归更新节点状态,实现状态联动效果
    • findUpdatedNode:在更新后的树中查找特定节点
  4. 状态同步逻辑

    • 父节点选中/取消时,所有子节点跟随变化
    • 子节点全部选中时,父节点自动选中
    • 子节点全部未选中时,父节点自动取消选中
  5. 组件渲染

    • 使用递归的renderTreeNodes函数渲染任意深度的树结构
    • 每个节点包含复选框和名称,子节点通过缩进展示层级关系
  6. 外部交互

    • 通过onChange回调将状态变化通知给父组件
    • 使用useEffect监听外部数据变化,同步更新内部状态

组件目录结构

在这里插入图片描述

代码实现

example\App.tsx

import React from "react";
import { Tree, type TreeNode } from "../packages";export default function App() {const data: TreeNode[] = [{id: 1,name: "Node 1",children: [{ id: 2, name: "Node 1.1", selected: true },{id: 3,name: "Node 1.2",selected: false,children: [{ id: 4, name: "Node 1.2.1", selected: false },{ id: 5, name: "Node 1.2.2", selected: false },],},],selected: true,},{ id: 6, name: "Node 2", selected: false },];function onChange(node: TreeNode) {console.log(node);}return (<div><Tree data={data} onChange={onChange} /></div>);
};

example\index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><div id="root"></div><script type="module" src="./main.tsx"></script>
</body>
</html>

example\main.tsx

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(<App />
);

packages\Tree\src\tree.tsx

import React, { useEffect, useState } from "react";
import { TreeNode, TreeProps } from "./types";// 检查所有子节点状态并返回父节点应该的状态
const checkChildrenStatus = (node: TreeNode): boolean => {if (!node.children || node.children.length === 0) {return !!node.selected;}// 检查是否所有子节点都被选中const allSelected = node.children.every((child) =>child.children && child.children.length > 0? checkChildrenStatus(child): !!child.selected);return allSelected;
};// 深度复制树数据
const deepCopyTreeData = (data: TreeNode[]): TreeNode[] => {return data.map((node) => ({...node,children: node.children ? deepCopyTreeData(node.children) : undefined,}));
};// 更新节点状态
const updateNodeStatus = (nodes: TreeNode[],nodeId: string | number,status: boolean
): TreeNode[] => {return nodes.map((node) => {if (node.id === nodeId) {// 更新当前节点const updatedNode = { ...node, selected: status };// 如果有子节点,递归更新所有子节点if (node.children && node.children.length > 0) {updatedNode.children = updateNodeStatus(node.children, nodeId, status);// 再对所有子节点应用相同的状态updatedNode.children = updatedNode.children.map((child) => ({...child,selected: status,children: child.children? child.children.map((grandChild) => ({...grandChild,selected: status,})): undefined,}));}return updatedNode;} else if (node.children && node.children.length > 0) {// 递归检查子节点const updatedChildren = updateNodeStatus(node.children, nodeId, status);// 检查更新后的子节点状态以决定当前节点状态const allChildrenSelected = updatedChildren.every((child) => !!child.selected);const noChildrenSelected = updatedChildren.every((child) => !child.selected);let nodeStatus = node.selected;if (allChildrenSelected) {nodeStatus = true;} else if (noChildrenSelected) {nodeStatus = false;}return {...node,selected: nodeStatus,children: updatedChildren,};}return node;});
};const Tree: React.FC<TreeProps> = ({ data, onChange }) => {const [treeData, setTreeData] = useState<TreeNode[]>(deepCopyTreeData(data));// 处理节点选择状态变化const handleNodeChange = (node: TreeNode, checked: boolean) => {// 创建更新后的树数据const updatedTreeData = updateNodeStatus(deepCopyTreeData(treeData),node.id,checked);// 更新状态setTreeData(updatedTreeData);// 找到更新后的节点并调用onChangeconst findUpdatedNode = (nodes: TreeNode[],id: string | number): TreeNode | undefined => {for (const n of nodes) {if (n.id === id) return n;if (n.children) {const found = findUpdatedNode(n.children, id);if (found) return found;}}return undefined;};const updatedNode = findUpdatedNode(updatedTreeData, node.id);if (updatedNode && onChange) {onChange(updatedNode);}};// 渲染树节点const renderTreeNodes = (nodes: TreeNode[]) => {return nodes.map((node) => (<div key={node.id} className="tree-node"><inputtype="checkbox"checked={!!node.selected}onChange={(e) => handleNodeChange(node, e.target.checked)}/><span>{node.name}</span>{node.children && node.children.length > 0 && (<div className="children-container" style={{ marginLeft: "20px" }}>{renderTreeNodes(node.children)}</div>)}</div>));};// 当外部data props变化时更新内部状态useEffect(() => {setTreeData(deepCopyTreeData(data));}, [data]);return <div className="tree">{renderTreeNodes(treeData)}</div>;
};export default Tree;

packages\Tree\src\types.tsx

export interface TreeNode {id: string | number;name: string;children?: TreeNode[];selected: boolean;
}export interface TreeProps {data: TreeNode[];onChange: (node: TreeNode) => void;
}

packages\Tree\style\index.tsx (暂时无样式编写)

packages\Tree\tree.tsx

import Tree from "./src/tree";export * from "./src/types";
export { Tree };

packages\index.tsx

import { Tree } from "./Tree";export * from "./Tree";
export { Tree };

packages\vite.d.ts

/// <reference types="vite/client" />

package.json (通过 npm init -y 生成)

这样直接启动会有一个警告:The CJS build of Vite's Node API is deprecated. See https://vite.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.

原因是 node 项目模块化未指定类型 type: module

{"name": "react-tree","version": "1.0.0","main": "index.js","type": "module","directories": {"example": "example"},"scripts": {"dev": "vite","build": "vite build"},"keywords": [],"author": "","license": "ISC","description": "","devDependencies": {"@types/node": "^22.15.29","@types/react": "^19.1.6","@types/react-dom": "^19.1.5","@vitejs/plugin-react-swc": "^3.10.0", // 编译 react"vite": "^6.3.5", // 构建工具 "vite-plugin-dts": "^4.5.4" // 生成打包后的声明文件(便于代码提示)},"dependencies": {"react": "^19.1.0","react-dom": "^19.1.0"}
}

tsconfig.json(通过 tsc --init 生成)

{"compilerOptions": {/* Visit https://aka.ms/tsconfig to read more about this file *//* Projects */// "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */// "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */// "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */// "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */// "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */// "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. *//* Language and Environment */"target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */// "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */"jsx": "react-jsx",                                /* Specify what JSX code is generated. */// "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */// "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */// "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */// "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */// "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */// "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */// "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */// "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */// "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. *//* Modules */"module": "commonjs",                                /* Specify what module code is generated. */// "rootDir": "./",                                  /* Specify the root folder within your source files. */// "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */// "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */// "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */// "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */// "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */// "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */// "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */// "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */// "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */// "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */// "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */// "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */// "resolveJsonModule": true,                        /* Enable importing .json files. */// "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */// "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. *//* JavaScript Support */// "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */// "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */// "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. *//* Emit */// "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */// "declarationMap": true,                           /* Create sourcemaps for d.ts files. */// "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */// "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */// "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */// "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */// "outDir": "./",                                   /* Specify an output folder for all emitted files. */// "removeComments": true,                           /* Disable emitting comments. */// "noEmit": true,                                   /* Disable emitting files from a compilation. */// "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */// "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */// "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */// "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */// "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */// "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */// "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */// "newLine": "crlf",                                /* Set the newline character for emitting files. */// "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */// "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */// "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */// "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */// "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */// "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. *//* Interop Constraints */// "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */// "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */// "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */"esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */// "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */"forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. *//* Type Checking */"strict": true,                                      /* Enable all strict type-checking options. */// "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */// "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */// "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */// "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */// "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */// "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */// "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */// "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */// "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */// "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */// "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */// "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */// "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */// "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */// "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */// "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */// "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */// "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. *//* Completeness */// "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */"skipLibCheck": true                                 /* Skip type checking all .d.ts files. */}
}

这样直接生成的会有一个问题:无法使用 JSX,除非提供了 "--jsx" 标志。 所以我们需要让 ts 配置(tsconfig.json)为支持 jsx 语法。"jsx": "react-jsx",

vite.config.ts

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import path from "node:path";export default defineConfig({plugins: [react()],root: path.resolve(__dirname, "example"), // 如果不配置,默认会从根目录找 index.htmlserver: {port: 3000,open: true,},
});

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/web/82293.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

tortoisegit 使用rebase修改历史提交

在 TortoiseGit 中使用 rebase 修改历史提交&#xff08;如修改提交信息、合并提交或删除提交&#xff09;的步骤如下&#xff1a; --- ### **一、修改最近一次提交** 1. **操作**&#xff1a; - 右键项目 → **TortoiseGit** → **提交(C)** - 勾选 **"Amend…

中科院报道铁电液晶:从实验室突破到多场景应用展望

2020年的时候&#xff0c;相信很多关注科技前沿的朋友都注意到&#xff0c;中国科学院一篇报道聚焦一项有望改写显示产业格局的新技术 —— 铁电液晶&#xff08;FeLC&#xff09;。这项被业内称为 "下一代显示核心材料" 的研究&#xff0c;究竟取得了哪些实质性进展…

论文阅读(六)Open Set Video HOI detection from Action-centric Chain-of-Look Prompting

论文来源&#xff1a;ICCV&#xff08;2023&#xff09; 项目地址&#xff1a;https://github.com/southnx/ACoLP 1.研究背景与问题 开放集场景下的泛化性&#xff1a;传统 HOI 检测假设训练集包含所有测试类别&#xff0c;但现实中存在大量未见过的 HOI 类别&#xff08;如…

74道Node.js高频题整理(附答案背诵版)

简述 Node. js 基础概念 &#xff1f; Node.js是一个基于Chrome V8引擎的JavaScript运行环境。它使得JavaScript可以在服务器端运行&#xff0c;从而进行网络编程&#xff0c;如构建Web服务器、处理网络请求等。Node.js采用事件驱动、非阻塞I/O模型&#xff0c;使其轻量且高效…

年龄是多少

有5个人坐在一起&#xff0c;问第五个人多少岁&#xff1f;他说比第四个人大两岁。问第四个人岁数&#xff0c;他说比第三个人大两岁。问第三个人&#xff0c;又说比第二个人大两岁。问第二个人&#xff0c;说比第一个人大两岁。最后问第一个人&#xff0c;他说是10岁。请问他们…

华为OD机试真题——模拟消息队列(2025A卷:100分)Java/python/JavaScript/C++/C语言/GO六种最佳实现

2025 A卷 100分 题型 本文涵盖详细的问题分析、解题思路、代码实现、代码详解、测试用例以及综合分析; 并提供Java、python、JavaScript、C++、C语言、GO六种语言的最佳实现方式! 2025华为OD真题目录+全流程解析/备考攻略/经验分享 华为OD机试真题《模拟消息队列》: 目录 题…

LangChain-结合GLM+SQL+函数调用实现数据库查询(三)

针对 LangChain-结合GLM+SQL+函数调用实现数据库查询(二)-CSDN博客 进一步简化 通过 LangChain 和大语言模型(GLM-4)实现了一个 AI 代理,能够根据自然语言提问自动生成 SQL 查询语句,并连接 MySQL 数据库执行查询,最终返回结果。 整个流程如下: 用户提问 → AI 生成 SQ…

ZLG ZCANPro,ECU刷新,bug分享

文章目录 摘要 📋问题的起因bug分享 ✨思考&反思 🤔摘要 📋 ZCANPro想必大家都不陌生,买ZLG的CAN卡,必须要用的上位机软件。在汽车行业中,有ECU软件升级的需求,通常都通过UDS协议实现程序的更新,满足UDS升级的上位机要么自己开发,要么用CANoe或者VFlash,最近…

第2期:APM32微控制器键盘PCB设计实战教程

第2期&#xff1a;APM32微控制器键盘PCB设计实战教程 一、APM32小系统介绍 使用apm32键盘小系统开源工程操作 APM32是一款与STM32兼容的微控制器&#xff0c;可以直接替代STM32进行使用。本教程基于之前开源的APM32小系统&#xff0c;链接将放在录播评论区中供大家参考。 1…

单元测试-断言常见注解

目录 1.断言 2.常见注解 3.依赖范围 1.断言 断言练习 package com.gdcp;import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test;//测试类 public class UserServiceTest {Testpublic void testGetGender(){UserService userService new UserService…

每日算法-250602

每日算法学习记录 - 250602 今天学习和复习了两道利用前缀和与哈希表解决的子数组问题&#xff0c;特此记录。 560. 和为 K 的子数组 题目 思路 本题的核心思想是利用 前缀和 与 哈希表 来优化查找过程。 解题过程 题目要求统计和为 k 的子数组个数。 我们首先预处理出一…

Arch安装botw-save-state

devkitPro https://blog.csdn.net/qq_39942341/article/details/148387077?spm1001.2014.3001.5501 cargo https://blog.csdn.net/qq_39942341/article/details/148387783?spm1001.2014.3001.5501 megaton https://blog.csdn.net/qq_39942341/article/details/148388164?spm…

STM32学习笔记---时钟树

目录 一、时钟树&#xff1a;M3---STM32F103 1、主要时钟来源 ​2、时钟系统线路分析 HSE时钟 HSI时钟 LSE时钟 LSI时钟 PPLCLK ---锁相环时钟 SYSCLK ---系统时钟 HCLK时钟 PCLK1时钟 PCLK2时钟 3、时钟树简图 4、构成部分作用分析 二、时钟树&#xff1a;M4-…

35.x64汇编写法(二)

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 本次游戏没法给 内容参考于&#xff1a;微尘网络安全 上一个内容&#xff1a;34.x64汇编写法&#xff08;一&#xff09; 上一个内容写了&#xff0c;汇编调…

钩子函数的作用(register_hook)

钩子函数仅在backward()时才会触发。其中&#xff0c;钩子函数接受梯度作为输入&#xff0c;返回操作后的梯度&#xff0c;操作后的梯度必须要输入的梯度同类型、同形状&#xff0c;否则报错。 主要功能包括&#xff1a; 监控当前的梯度&#xff08;不返回值&#xff09;&…

【头歌实验】Keras机器翻译实战

【头歌实验】Keras机器翻译实战 第1关&#xff1a;加载原始数据 编程要求 根据提示&#xff0c;在右侧编辑器补充代码&#xff0c;实现load_data函数&#xff0c;该函数需要加载path所代表的文件中的数据&#xff0c;并将文件中所有的内容按\n分割&#xff0c;转换成一个列表…

python中使用高并发分布式队列库celery的那些坑

python中使用高并发分布式队列库celery的那些坑 &#x1f31f; 简单理解&#x1f6e0;️ 核心功能&#x1f680; 工作机制&#x1f4e6; 示例代码&#xff08;使用 Redis 作为 broker&#xff09;&#x1f517; 常见搭配&#x1f4e6; 我的环境&#x1f4e6;第一个问题&#x1…

截图工具 Snipaste V2.10.7(2025.06.2更新)

—————【下 载 地 址】——————— 【​本章下载一】&#xff1a;https://pan.xunlei.com/s/VORklK9hcuoI6n_qgx25jSq2A1?pwde7bi# 【​本章下载二】&#xff1a;https://pan.quark.cn/s/7c62f8f86735 【百款黑科技】&#xff1a;https://ucnygalh6wle.feishu.cn/wiki/…

batch_size 参数最优设置

在深度学习训练中,batch_size(批量大小)的选择是一个需要权衡的问题,既不是越大越好,也不是越小越好,而是需要根据硬件资源、数据规模、模型复杂度和优化目标等因素综合决定。以下是详细分析:

【agent开发】部署LLM(一)

本周基本就是在踩坑&#xff0c;没什么实质性的进展 下载模型文件 推荐一个网站&#xff0c;可以简单计算下模型推理需要多大显存&#xff1a;https://apxml.com/tools/vram-calculator 我的显卡是RTX 4070&#xff0c;有12GB的显存&#xff0c;部署一个1.7B的Qwen3应该问题…