静态渲染svg
import React from 'react';
import * as d3 from "d3";
class TestCharts extends React.Component {
state = {
};
componentDidMount() {
this.drawChart();
}
drawChart = ()=> {
const data = [12, 5, 6, 6, 9, 10];
const w = 300;
const h = 200;
const svg = d3.select(".D3")
.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")
};
render() {
return (
<div>
<div className="D3" />
</div>
);
}
}
export default TestCharts;
https://www.jianshu.com/p/b12291a5dcb7
动态渲染svg
const data = [12, 5, 6, 6, 9, 10];
const w = 700;
const h = 200;
let svg;
class TestCharts extends React.Component {
state = {
};
componentDidMount() {
this.drawChart()
this.update()
}
// 关键在于把enter和渲染分开
drawChart = ()=> {
svg = d3.select(".D3")
.append("svg")
.attr("width", w)
.attr("height", h)
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
this.renderChart(svg)
}
renderChart = () => {
svg.selectAll("rect")
.data(data)
.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")
}
update = () => {
setInterval(()=>{
data.shift();
data.push(Math.round(Math.random() * 20));
this.renderChart()
},1000)
}
render() {
return (
<div>
<div className="D3" />
</div>
);
}
}
export default TestCharts;
动态渲染Dom
import React from 'react';
import * as d3 from "d3";
import './index.less';
const data = [10, 15, 30, 50, 80, 65, 55, 30, 20, 10, 8];
class TestCharts extends React.Component {
state = {
};
componentDidMount() {
this.update()
// this.mockData();
}
drawChart = ()=> {
// enter
d3.select(".D3").selectAll("div.h-bar")
.data(data)
.enter()
.append("div")
.attr("class", "h-bar")
.append("span")
// update
d3.select(".D3").selectAll("div.h-bar")
.data(data)
.style("width", d=>`${d*3}px`)
.select("span")
.text(d=>d)
// exit
d3.select(".D3").selectAll("div.h-bar")
.data(data)
.exit()
.remove()
}
update = () => {
setInterval(()=>{
data.shift();
data.push(Math.round(Math.random() * 100));
this.drawChart()
},1000)
}
render() {
return (
<div>
<div className="D3" />
</div>
);
}
}
export default TestCharts;