【问题标题】:d3 react js - Failed to execute 'createElementNS' on 'Document': The qualified name provided contains the invalid character ','d3 react js - 无法在“文档”上执行“createElementNS”:提供的限定名称包含无效字符“,”
【发布时间】:2017-05-27 08:47:27
【问题描述】:

我正在尝试在组件方法中创建 d3 折线图:

import React, {Component} from "react";
import {observer, inject} from "mobx-react";

import {line, select} from "d3"

@inject("store")
@observer
class PriceChart extends Component {
  constructor(props) {
    super(props)
    this.createLineChart = this.createLineChart.bind(this)
  }
  componentDidMount() {
    this.createLineChart()
  }
  componentDidUpdate() {
    this.createLineChart()
  }
  createLineChart() {

    const data = [
      {
        price: 100
      }, {
        price: 200
      }
    ]

    const node = this.node

    const priceLine = line().x((d) => 1).y((d) => d.price)

    select(node).append(priceLine(data))
  }
  render() {
    return <svg ref={node => this.node = node} width={800} height={800}></svg>
  }
}

export default PriceChart;

但我收到以下错误:

无法在“文档”上执行“createElementNS”:限定名称 提供的 ('M1,100L1,200') 包含无效字符 ','..

那么值 M1、L1 是从哪里来的?似乎 d3 正在向导致其出错的数据添加值?

【问题讨论】:

  • 似乎时间戳不被视为在您的 d3 图表上使用的有效数字,这就是为什么您是 gr
  • @Pineda 我试着玩弄我的输入 - 将所有价格更改为固定数字,将所有时间戳更改为 unix 时间戳,然后将 x 函数更改为始终返回 1,但我总是得到这个错误的一些变化 - 包含无效字符','..
  • @Pineda 将问题编辑为一个更简单的示例,但仍然显示问题

标签: javascript reactjs d3.js ecmascript-6


【解决方案1】:

这...

const priceLine = line().x((d) => 1).y((d) => d.price)

... 是一个行生成器

因此,它的作用是:如果您将给定的数据数组传递给它...

priceLine(data)

... 它返回一个带有路径命令的字符串。像这样:

"M1,100L1,200"

因此,将此字符串附加为 SVG 元素毫无意义。

解决方案

你想要的是附加一个 path 元素,并将这个字符串设置为它的d 属性。因此,应该是:

select(node).append("path")//append a path here
    .attr("d", priceLine(data))//and set its d attribute

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2020-07-15
    • 2020-02-04
    • 1970-01-01
    • 2014-12-04
    • 2017-12-04
    相关资源
    最近更新 更多