如何在ReactJS / NextJS中使用D3?

8
我想添加一个d3图表,按照教程操作但是没有任何反应。我不确定useEffect()是否在正确的"时机"上使用,是否应该使用componentDidMount,或者是否添加元素的方法不正确...看起来我在这里漏了些什么!
import React from 'react';
import * as d3 from "d3";
import { useEffect } from 'react';

function drawChart() {
  const data = [12, 5, 6, 6, 9, 10];
  const h = 100;
  const w = 100;
  const svg = d3.select("body")
    .append("svg")
    .attr("width", w)
    .attr("height", h)
    .style("margin-left", 100);
                  
    svg.selectAll("rect")
      .data(data)
      .enter()
      .append("rect")
      .attr("x", (d, i) => i * 70)
      .attr("y", (d, i) => h - 10 * d)
      .attr("width", 65)
      .attr("height", (d, i) => d * 10)
      .attr("fill", "green")
}


const chart: React.FunctionComponent = () => {
  useEffect(() => {
    drawChart();
  }, []);
  
  return (
    <div>
    </div>
  );
};
export default chart;

2
“什么叫‘完全没有反应’?”你的图表是有效的 - Zsolt Meszaros
1个回答

15
在这个例子中可能会导致错误的原因是d3将SVG附加到body上,这完全超出了React DOM的范围。更好的方法是在JSX中添加SVG,并使用引用(在钩子中使用useRef)告诉D3图表必须呈现的位置:
import * as React from "react";
import * as d3 from "d3";

function drawChart(svgRef: React.RefObject<SVGSVGElement>) {
  const data = [12, 5, 6, 6, 9, 10];
  const h = 120;
  const w = 250;
  const svg = d3.select(svgRef.current);

  svg
    .attr("width", w)
    .attr("height", h)
    .style("margin-top", 50)
    .style("margin-left", 50);

  svg
    .selectAll("rect")
    .data(data)
    .enter()
    .append("rect")
    .attr("x", (d, i) => i * 40)
    .attr("y", (d, i) => h - 10 * d)
    .attr("width", 20)
    .attr("height", (d, i) => d * 10)
    .attr("fill", "steelblue");
}

const Chart: React.FunctionComponent = () => {
  const svg = React.useRef<SVGSVGElement>(null);

  React.useEffect(() => {
    drawChart(svg);
  }, [svg]);

  return (
    <div id="chart">
      <svg ref={svg} />
    </div>
  );
};

export default Chart;

这里是一个示例的 CodePen


1
找到了这篇文章这篇文章,可能会有所帮助。还有这篇文章是关于SSR的。 - Gangula
在NextJs 13上遇到了以下错误:错误:函数组件不能有字符串引用。我们建议使用useRef()代替。在这里了解更多关于安全使用引用的信息:https://reactjs.org/link/strict-mode-string-ref - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接