我一直遵循this tutorial在我的React应用程序中放置用d3制作的条形图,但是当我尝试调用const svgCanvas = d3.select(this.canvas).append("svg")
时出现错误,这使我认为我的{{1 }}引用设置错误。
当我放
this.canvas
在引发错误的命令之前,这些是输出:
console.log(this.canvas);
console.log(d3.select(this.canvas));
{current: div}
current: null
__proto__: Object
以下是从另一个文件调用的BarChart组件。
R {_groups: Array(1), _parents: Array(1)}
_groups: Array(1)
0: Array(1)
0:
current: null
__proto__: Object
length: 1
__proto__: Array(0)
length: 1
__proto__: Array(0)
_parents: Array(1)
0: null
length: 1
__proto__: Array(0)
__proto__: Object
这应该已经制作出了本教程中显示的条形图,但是我却在import React from 'react';
import * as d3 from 'd3';
class BarChart extends React.Component {
public canvas: any;
public constructor(props: any) {
super(props);
this.canvas = React.createRef();
}
public componentDidMount() {
const data = [2, 4, 2, 6, 8];
this.drawBarChart(data);
}
public drawBarChart(data: number[]) {
const canvasHeight = 400;
const canvasWidth = 600;
const scale = 20;
const help = d3.select(this.canvas);
const svgCanvas = d3.select(this.canvas)
.append("svg") // ERROR RAISED ON THIS LINE
.attr("width", canvasWidth)
.attr("height", canvasHeight)
.style("border", "1px solid black");
console.log(svgCanvas);
svgCanvas.selectAll("rect")
.data(data).enter()
.append("rect")
.attr("width", 40)
.attr("height", ((datapoint: number) => datapoint * scale))
.attr("fill", "orange")
.attr("x", (datapoint: number, iteration: number) => iteration * 45)
.attr("y", ((datapoint: number) => canvasHeight - datapoint * scale));
}
public render() {
return (
<div ref={this.canvas} />
);
}
}
export default BarChart;
的行上得到了TypeError: Cannot read property 'createElementNS' of undefined
。
编辑:https://pasteboard.co/IwQ441d.png上的控制台日志屏幕截图
答案 0 :(得分:0)
通过将d3.select(this.canvas)
更改为d3.select(this.canvas.current)
,我能够避免此错误。