如何让react-drag-hierarchy-tree的父级与子级节点高度一致
解决react-drag-hierarchy-tree对齐间隙及行间链接表格实现问题
一、修复树组件的对齐与高度一致性问题
1. 修正重复节点ID
你的数据中存在多个节点共用同一ID的情况(如多个id:2、id:3),这会导致组件渲染异常,是引发对齐问题的潜在原因。请确保每个节点ID唯一:
const data = { id: 1, label: 'Main', children: [ { id: 2, label: 'Parent', children: [ { id: 3, label: 'child 1', children: [ { id: 4, label: 'child 2' }, { id: 5, label: 'child 2' }, { id: 6, label: 'child 2' }, { id: 7, label: 'child 2' }, ], }, { id: 8, label: 'child 1' }, { id: 9, label: 'child 1' }, { id: 10, label: 'child 1' }, ], }, { id: 11, label: 'Parent' }, { id: 12, label: 'Parent' }, { id: 13, label: 'Parent' }, ], };
2. 自定义CSS消除间隙并统一节点高度
通过覆盖组件默认样式,强制所有节点高度一致并消除多余间隙。在项目中添加以下CSS:
/* 统一所有节点高度,确保对齐 */ .org-tree-node { height: 60px; /* 根据需求调整高度 */ display: flex; align-items: center; } /* 移除节点容器的默认边距和内边距 */ .org-tree-node-wrapper { margin: 0 !important; padding: 0 !important; } /* 调整水平布局下子节点的左侧间距 */ .org-tree-horizontal .org-tree-node-children { padding-left: 0 !important; }
将上述CSS导入到你的组件文件中,或添加到全局样式表。
二、实现带有行间链接的表格
若要创建带有父子行连接线的表格,可通过CSS伪元素绘制连接线。以下是示例实现:
表格组件代码
import React from 'react'; import './TableWithLinks.css'; const TableWithLinks = () => { return ( <table className="tree-table"> <thead> <tr> <th>节点名称</th> <th>操作</th> </tr> </thead> <tbody> <tr className="parent-row"> <td>Main</td> <td><button>编辑</button></td> </tr> <tr className="child-row"> <td>Parent 1</td> <td><button>编辑</button></td> </tr> <tr className="grandchild-row"> <td>Child 1</td> <td><button>编辑</button></td> </tr> <tr className="child-row"> <td>Parent 2</td> <td><button>编辑</button></td> </tr> </tbody> </table> ); }; export default TableWithLinks;
配套CSS(TableWithLinks.css)
.tree-table { border-collapse: collapse; width: 100%; } .tree-table th, .tree-table td { border: 1px solid #ddd; padding: 8px 16px; position: relative; } /* 绘制子行与父行的垂直连接线 */ .child-row::before { content: ''; position: absolute; left: 8px; top: 0; bottom: 0; width: 2px; background-color: #ccc; } /* 绘制孙行与子行的垂直连接线 */ .grandchild-row::before { content: ''; position: absolute; left: 24px; top: 0; bottom: 0; width: 2px; background-color: #ccc; } /* 绘制孙行与子行的水平连接线 */ .grandchild-row::after { content: ''; position: absolute; left: 8px; top: 50%; width: 16px; height: 2px; background-color: #ccc; }
内容的提问来源于stack exchange,提问作者Abdur Rahman B
相关产品推荐
相关产品推荐

