reactjs - TypeError:无法读取未定义的属性“createElementNS”
问题描述
我正在按照本教程在我的 React 应用程序中放置一个使用 d3 制作的条形图,但是当我尝试调用时出现错误,const svgCanvas = d3.select(this.canvas).append("svg")
这让我认为我的this.canvas
ref 设置错误。
当我把
console.log(this.canvas);
console.log(d3.select(this.canvas));
在引发错误的命令之前,这些是输出:
{current: div}
current: null
__proto__: Object
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
以下是从另一个文件调用的 BarChart 组件。
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
使用.append('svg')
.
编辑: https ://pasteboard.co/IwQ441d.png 的控制台日志截图
解决方案
我可以通过更改d3.select(this.canvas)
为d3.select(this.canvas.current)
.
推荐阅读
- android - 如何知道 RecyclerView 中的项目是否已完成拖动事件?
- reactjs - 如何将带有formData的正文作为密钥获取api发送
- reactjs - 从 Map 访问值
> - python - 提高 spaCy 3 ner 的实体精度
- javascript - 无响应页面 - face-api.js
- python - 如何在 TK、python 中使用布尔变量?
- jquery - 为什么设置了 data-plugin="counterup" 时标签内容没有更新
- sqlite - 在 Windows 10 中安装 sqlite3
- ios - 是否可以根据 SDK 版本隐藏代码
- javascript - 查找数组中最大和最小数字的索引