嘿,我正在尝试学习react和d3.js。现在,我所有的代码都在一个js文件中。我试图将颜色阵列与对象阵列结合起来,然后可以使用d3将其吐出到饼图中。
之前,我能够通过“ react way”并排放置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开头,然后是创建图像所需的其余数据。我想我可能正在处理错误。朝正确方向迈出的任何一步将不胜感激。谢谢。