首页 > 解决方案 > TypeError:无法读取未定义的属性“createElementNS”

问题描述

我正在按照本教程在我的 React 应用程序中放置一个使用 d3 制作的条形图,但是当我尝试调用时出现错误,const svgCanvas = d3.select(this.canvas).append("svg")这让我认为我的this.canvasref 设置错误。

当我把

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 的控制台日志截图

标签: reactjstypescriptd3.js

解决方案


我可以通过更改d3.select(this.canvas)d3.select(this.canvas.current).


推荐阅读