【问题标题】:How to render svg.node() object in React?如何在 React 中渲染 svg.node() 对象?
【发布时间】:2022-12-11 13:24:28
【问题描述】:

我正在制作 D3 圆包布局。

    const BubbleChart = ({ bubblesData, height, width }: BubbleChartProps) => {
    
      const packData = (size: any) => {
        return d3.pack().size(size).padding(3);
      }
    
      const makeHierarchy = () => {
        return d3.hierarchy({ children: bubblesData }).sum((d:any) => d.count);
      }
    
      const makeBubbles = () => {
        const hierachalData = makeHierarchy();
        const packLayout = packData([width - 2, height - 2]);
        const root = packLayout(hierachalData);
    
        const svg = d3.create("svg")
        .attr("width", width)
        .attr("height", height);
    
        const leaf = svg.selectAll("g")
          .data(root.leaves())
          .enter().append("g")
            .attr("transform", d => `translate(${d.x + 1},${d.y + 1})`);
    
        leaf.append("circle")
        .attr("r", d => {
          const minValue = d3.min(bubblesData, (d) => d.count)
          const maxValue = d3.max(bubblesData, (d) => d.count)
          let scale = d3.scaleSqrt()
            .domain([0, maxValue as unknown as number])
            .range([0,d.r]);
          return scale(minValue as unknown as number);
          })
          .attr("fill", "#d9edf7")
  
        return svg.node();
      }
    
      return (
        <div id="chart">{makeBubbles()}</div>
      )
    }
    
 export default BubbleChart

问题是我无法渲染 svg.node() 因为类型 pf svg.node() 是对象。我收到以下错误:

对象作为 React 子项无效(找到:[object SVGSVGElement])。如果您打算呈现子项集合,请改用数组。

有什么办法可以渲染这个吗?

【问题讨论】:

    标签: reactjs d3.js


    【解决方案1】:

    也遇到了这个问题。解决方案是使用 ref 到 html 元素并使用 ref.current.appendChild(svgObject)。

    Render SVGSVGElement in React JS without dangerouslySetInnerHtml

    【讨论】:

      猜你喜欢
      • 2021-01-07
      • 2019-03-19
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      相关资源
      最近更新 更多