嘿伙计们,我正在努力学习反应和d3.js.现在我的所有代码都在一个js文件中 . 我试图用一系列对象将颜色数组结合起来然后可以用d3吐出一个饼图 .
之前我能够创建一个带有20个彩色盒子的svg并排“反应方式” . 现在,我正在尝试使用相同类型的结构移植饼图来创建组件 .
这就是我所拥有的 .
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
//import './index.css';
//import registerServiceWorker from './registerServiceWorker';
import * as d3 from 'd3';
//import data from './listings.json';
var data = [{"letter":"q","presses":1},{"letter":"w","presses":5},{"letter":"e","presses":2}];
// Component that draws a single color swatch
const Arc = ({ color, d }) => (
<path className="arc" d={d} style={{fill: color}} />
);
// Draws an entire color scale
class Arcs extends Component {
pieWidth = 300;
pieHeight = 300;
radius = Math.min(this.pieWidth, this.pieHeight) / 2;
colors = ["red", "green", "blue"];
width = d3.scaleBand().domain(d3.range(3));
pie = d3.pie()
.value(function(d) { return d.presses; })(data);
arc = d3.arc()
.outerRadius(this.radius - 10)
.innerRadius(0);
labelArc = d3.arc()
.outerRadius(this.radius - 40)
.innerRadius(this.radius - 40);
/*
//This bit was from an example and I have recreated it in the render function below
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 +")"); // Moving the center point. 1/2 the width and 1/2 the height
//this bit is giving me trouble: the .data(pie).enter() I need to recreate in react somehow... I think this applies it to all the arcs at once but they get created one at a time in the render function so I'm stuck.
var g = svg.selectAll("arc")
.data(pie)
.enter().append("g")
.attr("class", "arc");
}
*/
componentWillMount() {
this.updateD3(this.props);
}
componentWillUpdate(newProps) {
this.updateD3(newProps);
}
updateD3(props) {
this.width.range([0, props.width]);
}
render() {
return (
<svg width={this.pieWidth} height={this.pieHeight}>
<g transform={'translate(' + this.pieWidth/2 + ',' + this.pieHeight/2 + ')'}>
{d3.range(3).map(i => (
<Arc d={this.pie} color={this.colors[i]} key={i} />
))}
</g>
</svg>
)
}
}
ReactDOM.render(<Arcs />, document.getElementById('root'));
//registerServiceWorker();
这是输出:
<div id="root">
<svg width="300" height="300">
<g transform="translate(150,150)">
<path class="arc" d="[object Object],[object Object],[object Object]" style="fill: red;"></path>
<path class="arc" d="[object Object],[object Object],[object Object]" style="fill: green;"></path>
<path class="arc" d="[object Object],[object Object],[object Object]" style="fill: blue;"></path>
</g>
</svg>
</div>
path元素中的'd'值应以M或m开头,然后是创建图像所需的其余数据 . 我想我也许错了 . 任何正确方向的步骤将不胜感激 . 谢谢 .