将npm+parcel+react配置完成后
npm i d3
import * as d3 from "d3";
使用React useEffect和useRef
import React, { useEffect, useRef } from 'react';
示例代码:
import React, { useEffect, useRef } from 'react';
import * as d3 from "d3";
import "../styles/LineChart.css";
export default function LineChart() {
const d3Chart = useRef();
useEffect(()=>{
// attr
var margin = {top: 10, right: 30, bottom: 20, left: 60};
var width = 700 - margin.right - margin.left, height = 500 - margin.top - margin.bottom;
var svg = d3.select(d3Chart.current)
.attr("width", width+margin.right+margin.left)
.attr("height", height+margin.top+margin.bottom+40)
.append("g")
.attr("transform", "translate(" + margin.left + ", " + margin.top + ")");
// 异步获取数据并画图
d3.csv("https://raw.githubusercontent.com/zih-an/visualization/master/lab1/2.csv")
.then(d => chart_lines(d, svg, margin, width, height));
},[]);
return (
<div>
<p>This is a D3 and Component test.</p>
<svg ref={d3Chart}></svg>
</div>
);
}
function chart_lines(data, svg, margin, width, height) {
// 画图
}