You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让react-d3-tree节点名称显示在节点圆圈下方?

问题:react-d3-tree 节点文本移至圆圈下方

我正在用react-d3-tree构建树形图,想把节点名称文本移到节点圆圈的下方提升可读性。已经通过CSS类成功修改了节点颜色,但不管是CSS还是主代码里都没法调整文本位置。查资料发现textLayout属性已经被移除,找不到合适的替代方案。

相关代码如下:

homePage.js

import React from 'react';
import './common.css';
import Tree from 'react-d3-tree';

export class HomePage extends React.Component {
  constructor(props) {
    super(props);
    const onboardingTree = {
      name: '提交权限申请',
      children: [
        {
          name: '完成培训',
          attributes: {
            详情: '请联系相关人员报名培训课程',
          },
          children: [
            {
              name: '完成测试',
            },
          ],
        },
      ],
    };
    this.state = {
      onboardingTree: onboardingTree,
    };
  }

  componentDidMount() {
    const dimensions = this.treeContainer.getBoundingClientRect();
    this.setState({
      translate: {
        x: dimensions.width / 10,
        y: dimensions.height / 10,
      },
    });
  }

  render() {
    return (
      <div>
        <div className="container mx-auto mt-14 pt-1 ">
          <br />
          <div className="flex mt-1 mb-3 pl-4  justify-between">
            <p className="page-title">欢迎页</p>
          </div>
          <hr className="my-2" />
          <div className=" flex flex-wrap  ">
            <div style={{ width: '650px', height: '290px', textAlign: 'left' }} className="w-full ml-5 mt-4 py-1 px-3 border rounded-2xl ">
              <div className="w-full">
                <p className="py-2 lead font-bold ">入职流程</p>
                <div className="flex justify-center pt-2">
                  <div style={{ width: '1000px', height: '100vh' }} ref={(tc) => (this.treeContainer = tc)}>
                    <Tree
                      data={this.state.onboardingTree}
                      translate={this.state.translate}
                      collapsible={false}
                      rootNodeClassName="node__root"
                      branchNodeClassName="node__branch"
                      leafNodeClassName="node__leaf"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default HomePage;

common.css

.node__root > circle {
  fill: rgb(255, 255, 255);
  stroke: #e21717;
}

.node__branch > circle {
  fill: rgb(255, 255, 255);
  stroke: #f8e327f3;
}

.node__leaf > circle {
  fill: rgb(255, 255, 255);
  stroke: #10e256;
}

当前效果:文本默认在节点圆圈右侧,需要移至圆圈下方。


解决方案

由于textLayout属性已被移除,推荐使用自定义节点标签组件(nodeLabelComponent)来控制文本位置,这是react-d3-tree官方推荐的灵活定制方案。

步骤1:创建自定义标签组件

在HomePage组件中添加一个自定义组件,将文本放在节点圆圈的下方,居中对齐:

const CustomNodeLabel = ({ node }) => (
  <g transform="translate(0, 20)"> {/* 向下偏移20px,可根据需求调整 */}
    <text
      x="0"
      y="0"
      textAnchor="middle"
      dominantBaseline="middle"
      className="node-label"
    >
      {node.name}
    </text>
    {/* 如需显示节点属性,可添加以下代码 */}
    {node.attributes && Object.entries(node.attributes).map(([key, value]) => (
      <text
        key={key}
        x="0"
        y="15"
        textAnchor="middle"
        dominantBaseline="middle"
        className="node-attribute"
        fontSize="12"
        fill="#666"
      >
        {`${key}: ${value}`}
      </text>
    ))}
  </g>
);

步骤2:在Tree组件中引用自定义标签

修改Tree组件的props,添加自定义标签配置:

<Tree
  data={this.state.onboardingTree}
  translate={this.state.translate}
  collapsible={false}
  rootNodeClassName="node__root"
  branchNodeClassName="node__branch"
  leafNodeClassName="node__leaf"
  nodeLabelComponent={CustomNodeLabel} // 新增该行引用自定义组件
/>

步骤3:可选CSS优化

如果需要调整文本样式,可在common.css中添加:

.node-label {
  font-size: 14px;
  font-weight: 500;
  fill: #333;
}

.node-attribute {
  font-size: 12px;
  fill: #666;
}

原理说明

自定义nodeLabelComponent会替换默认的文本标签,通过<g>标签的transform属性将文本整体向下偏移,配合textAnchor="middle"实现居中,完美将文本放在节点圆圈的下方。


内容的提问来源于stack exchange,提问作者Lucy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:02:10