条形图中缺少矩形

时间:2019-08-02 04:19:53

标签: reactjs d3.js

我是新来的d3。我正在尝试我们的barChart,但只看到一个重叠的矩形。检查每个rect元素,我发现期望x, y, height and width。但我不明白为什么其他三个矩形未显示。 render single bar

html

BarChart.js

import React, { Component } from 'react'
import { scaleLinear } from 'd3-scale';
import { max } from 'd3-array';
import { select } from 'd3-selection';

export default class BarChart extends Component {
  constructor(props) {
    super(props)
  }

  componentDidMount() {
    this.createBarChart()
  }

  componentDidUpdate() {
    this.createBarChart()
  }

  createBarChart = () => {
    const node = this.node
    const dataMax = max(this.props.data)
    const yScale = scaleLinear()
    .domain([0, dataMax])
    .range([0, this.props.size[1]])

    select(node)
    .selectAll('rect') 
    .data(this.props.data)
    .enter() // placeholder selection
    .append('rect') // return a selection of appended rects

    select(node)
    .selectAll('rect') // rect selection
    .data(this.props.data) // update data in rect selection
    .exit()
    .remove() // exit and remove rects

    select(node)
    .selectAll('rect') // rect selection
    .data(this.props.data) // join data with rect selection
    .style('fill', '#fe9922')
    .attr('x', (d, i) => i * 25)
    .attr('y', d => this.props.size[1] - yScale(d))
    .attr('height', d => yScale(d))
    .attr('width', 25)
  }

  render() {
    return (
      // Pass a reference to the node for D3 to use
      <svg ref={node => this.node = node}
            width={this.props.width} height={this.props.height}
      >

      </svg>
    )
  }
}

使用this answer,我更新了createBarChart(),但仍然看到相同的奇数渲染。

  createBarChart = () => {
    const node = this.node
    const dataMax = max(this.props.data)
    const yScale = scaleLinear()
    .domain([0, dataMax])
    .range([0, this.props.size[1]])

    this.rects = select(node)
    .selectAll('rect')
    .data(this.props.data)

    this.rects
    .exit()
    .remove()

    this.rects = this.rects.enter()
    .append('rect')
    .merge(this.rects)
    .style('fill', '#fe9922')
    .attr('x', (d, i) => i * 25)
    .attr('y', d => this.props.size[1] - yScale(d))
    .attr('height', d => yScale(d))
    .attr('width', 25)
  }

App.js

        <div>
          <BarChart  data={[50,10,11,13]} size={[500,500]}/>
        </div>

1 个答案:

答案 0 :(得分:0)

发现了错误,我传递了错误的道具,在这种情况下this.props.widththis.props.height不存在。当我的rect的高度溢出svg框时,我只能看到一个最长的条,而看不到其他较短的条。

      <svg ref={node => this.node = node}
            width={this.props.size[0]} height={this.props.size[1]}
      >


      </svg>