首页 > 解决方案 > 类型“HierarchyNode”上不存在属性“x”'

问题描述

import React, { useRef, useEffect } from "react";
import { select, hierarchy, tree } from "d3";

function ThreeChart({ data }: any) {
  const svgRef = useRef(null);
  const wrapperRef = useRef(null);

  useEffect(() => {
    const svg = select(svgRef.current);

    const root = hierarchy(data);
    svg
      .selectAll(".node")
      .data(root.descendants())
      .join("circle")
      .attr("class", "node")
      .attr("fill", "black").attr("cx", node => node.x) // Property 'x' does not exist 
      .attr("r", 4)
  }, [data]);

  return (
    <div ref={wrapperRef} style={{ marginBottom: "2rem" }}>
      <svg ref={svgRef}></svg>
    </div>
  );
}

export default ThreeChart;

我认为这非常简单明了,但是因为我是打字稿的新手,所以我似乎无法弄清楚,我应该在什么地方或在哪里声明我的类型,我已经尝试过了,但它不起作用:

interface DataProps {
  children: DataProps[];
  depth: number;
  height: number;
  x: number;
  y: number;
  data: Data
}
interface Data {
  name: string;
  children: Data[]
}

通行证数据如下所示:

const data = {
  name: "1",
  children: [
    {
      name: "1.1",
      children: [
        {
          name: "1.1.1",
        },
        {
          name: "1.1.2",
        },
        {
          name: "1.1.3",
        },
      ],
    },
    {
      name: "1.2",
    },
  ],
};

这是 console.log(root) :在此处输入图像描述

标签: typescriptd3.js

解决方案


const data = {
name: "1",
children: [
  {
  name: "1.1",
  children: [
    {
      name: "1.1.1",
    },
    {
      name: "1.1.2",
    },
    {
      name: "1.1.3",
    },
  ],
},
{
  name: "1.2",
},
],
};

数据对象不包含 x 字段,正如我所见,它仅包含名称和子字段。因此,您必须设置字段 x 然后才使用它


推荐阅读