Tree 树形组件封装

article/2025/7/4 17:31:25

整体思路

  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.hkcw.cn/article/WXsJcMJxYY.shtml

相关文章

数据结构与算法:图论——拓扑排序

基础与模板&#xff1a; 有两个Kahn和DFS两个算法 下面给出Kahn的算法模板 #include<iostream> #include<vector> #include<queue> using namespace std;vector<int> topologicalSortKahn(int num, const vector<pair<int, int>>& re…

现代语言模型中的分词算法全解:从基础到高级

基础分词&#xff08;Naive Tokenization&#xff09; 最简单的分词方式是基于空格将文本拆分为单词。这是许多自然语言处理&#xff08;NLP&#xff09;任务中常用的一种分词方法。 text "Hello, world! This is a test." tokens text.split() print(f"Tok…

Deepseek给出的8255显示例程

#include <stdio.h> #include <conio.h> #include <dos.h>// 定义8255端口地址 (根据原理图译码确定) #define PORT_8255_A 0x8000 // PA端口地址 #define PORT_8255_B 0x8001 // PB端口地址 #define PORT_8255_C 0x8002 // PC端口地址 #define PORT_8255…

计算机组成原理——CPU的功能和基本结构

5.1 CPU的功能和基本结构 整理自beokayy课程视频 1.CPU的组成 程序计数器&#xff08;PC&#xff09;&#xff1a; 存放即将执行指令的地址。顺序执行时&#xff0c;PC“1”形成下条指令地址。在有的机器中&#xff0c;PC本身具有“1”计数功能&#xff0c;也有的机器借助运算…

LINUX62软链接;核心目录;错题:rpm -qa |grep<包名> 、rpm -ql<包名>;rm -r rm -rf;合并 cat

硬链接 软链接 软链接 [rootcode axel-2.4]# which axel /usr/bin/which: no axel in (/sbin:/bin:/usr/sbin:/usr/bin) [rootcode axel-2.4]# ln -s /opt/axel/bin/axel /usr/bin [rootcode axel-2.4]# axel https://mirrors.aliyun.com/centos-stream/ 初始化下载: https:/…

[Java恶补day13] 53. 最大子数组和

休息了一天&#xff0c;开始补上&#xff01; 给你一个整数数组 nums &#xff0c;请你找出一个具有最大和的连续子数组&#xff08;子数组最少包含一个元素&#xff09;&#xff0c;返回其最大和。 子数组是数组中的一个连续部分。 示例 1&#xff1a; 输入&#xff1a;nums …

C++哈希表:冲突解决与高效查找

引入 通过CSTL库中的unordered_map和unordered_set的学习&#xff0c;我们还需要其底层结构是什么&#xff0c;如何实现的&#xff0c;本节重点讲解哈希 哈希概念 顺序结构以及平衡树中&#xff0c;元素关键码与其存储位置之间没有对应关系&#xff0c;因此在查找一个元素是…

【科研绘图系列】R语言绘制论文比较图(comparison plot)

禁止商业或二改转载,仅供自学使用,侵权必究,如需截取部分内容请后台联系作者! 文章目录 介绍加载R包数据下载导入数据数据预处理画图1画图2画图3系统信息介绍 这篇文章详细介绍了如何使用R语言进行工作流中不同步骤的比较分析,包括数据预处理、特征选择、模型训练和结果可…

录屏不再难,从功能到体验深度测评

在日常工作和学习中&#xff0c;录屏是一项非常常见的需求&#xff0c;比如制作教程、记录操作过程、录制线上会议等。市面上虽然有不少录屏工具&#xff0c;但要么功能受限&#xff0c;要么广告繁多&#xff0c;甚至需要付费解锁高级功能&#xff0c;使用起来并不方便。 这款…

2023年12月6级第一套第一篇

在这里才找完题干&#xff0c;所以答案在下一句虽然不重要&#xff0c;不用看&#xff0c;重要的是但是 A&#xff1a;critic在虽然部分&#xff0c;不重要&#xff0c; c选项前面的部分也在虽然部分&#xff0c;不重要定位的下一句就是答案&#xff0c;还有冒号&#xff0c;看…

Linux --TCP协议实现简单的网络通信(中英翻译)

一、什么是TCP协议 1.1 、TCP是传输层的协议&#xff0c;TCP需要连接&#xff0c;TCP是一种可靠性传输协议&#xff0c;TCP是面向字节流的传输协议&#xff1b; 二、TCPserver端的搭建 2.1、我们最终好实现的效果是 客户端在任何时候都能连接到服务端&#xff0c;然后向服务…

多群组部署

相关概念 星形拓扑和并行多组 如下图&#xff0c;星形组网拓扑和并行多组组网拓扑是区块链应用中使用较广泛的两种组网方式。 星形拓扑&#xff1a;中心机构节点同时属于多个群组&#xff0c;运行多家机构应用&#xff0c;其他每家机构属于不同群组&#xff0c;运行各自应用…

unidbg patch 初探 微博deviceId 案例

声明 本文章中所有内容仅供学习交流使用&#xff0c;不用于其他任何目的&#xff0c;抓包内容、敏感网址、数据接口等均已做脱敏处理&#xff0c;严禁用于商业用途和非法用途&#xff0c;否则由此产生的一切后果均与作者无关&#xff01; 逆向过程 看了b站迷人瑞信那个由于是…

如何自定义WordPress主题(5个分步教程)

如果您已经安装了一个 WordPress 主题&#xff0c;但它不太适合您&#xff0c;您可能会感到沮丧。在定制 WordPress 主题方面&#xff0c;您有很多选择。 挑战在于找到正确的方法。 在本篇文章中&#xff0c;我将引导您了解自定义 WordPress 主题的各种选项&#xff0c;帮助您…

【兽医处方专用软件】佳易王兽医电子处方软件:高效智能的宠物诊疗管理方案

一、软件概述与核心优势 &#xff08;一&#xff09;试用版获取方式 资源下载路径&#xff1a;进入博主头像主页第一篇文章末尾&#xff0c;点击卡片按钮&#xff1b;或访问左上角博客主页&#xff0c;通过右侧按钮获取详细资料。 说明&#xff1a;下载文件为压缩包&#xff…

【nssctf第三题】[NSSCTF 2022 Spring Recruit]easy C

这是题目&#xff0c;下载附件打开是个C文件 #include <stdio.h> #include <string.h>int main(){char a[]"wwwwwww";char b[]"dvxbQd";//try to find out the flagprintf("please input flag:");scanf(" %s",&a);if…

DAY41 CNN

可以看到即使在深度神经网络情况下&#xff0c;准确率仍旧较差&#xff0c;这是因为特征没有被有效提取----真正重要的是特征的提取和加工过程。MLP把所有的像素全部展平了&#xff08;这是全局的信息&#xff09;&#xff0c;无法布置到局部的信息&#xff0c;所以引入了卷积神…

助力活力生活的饮食营养指南

日常生活中&#xff0c;想要维持良好的身体状态&#xff0c;合理的营养补充至关重要。对于易受身体变化困扰的人群来说&#xff0c;更需要从饮食中摄取充足养分。​ 蛋白质是身体的重要 “建筑材料”&#xff0c;鱼肉、鸡肉、豆类制品富含优质蛋白&#xff0c;易于消化吸收&am…

CA-Net复现

复现结果–Dice&#xff1a;90.093802&#xff0c;Jaccard&#xff1a;82.077802&#xff0c;95HD&#xff1a;6.89387267&#xff0c;ASD&#xff1a;1.76263258&#xff0c;与原文一致 感想 第16篇完全复现的论文

【具身智能】【机械臂】各类机械臂对比

选购指标 选购指标 说明机械-负载1w以内通常200g负载&#xff08;一袋酸奶&#xff09;&#xff0c;1w-5w 1kg负载&#xff08;1L饮料&#xff09;&#xff0c;5w 3kg负载机械-精度越贵精度越高机械-夹爪是否支持更换夹爪等&#xff0c;能否支持力控夹爪机械-AGV扩展 …