d3反应图表宽度计算

时间:2016-02-19 09:55:29

标签: d3.js reactjs

我使用react-faux-dom在React组件中有一个简单的d3 barChart。

为了创建图表

    let svg = d3.select(ReactFauxDOM.createElement('div')).append('svg')
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)

然后回去做出反应:

    let graph = svg.node().toReact();

这很有效,可以让我快速创建d3图。我可以通过将其作为父组件的prop来传递来管理宽度。

有人知道更优雅的方式吗? 我想选择一个元素,并阅读.offsetWidth proprierty。

但是,当然,当我这样做时:

    svg.offsetWidth

我得到了未定义......

任何想法?

1 个答案:

答案 0 :(得分:0)

我知道这个问题有点老了,但是因为上周我一直在寻找解决方案而无法找到我喜欢的答案,我想我会发布它。

我不喜欢在我的每个组件中包含ReactDOM来测量,我还要求更新宽度变化。出于这些原因,我最终得到了类似于Olical提到的解决方案,并且还包含了react-resize-detector

import React, {Component} from 'react';
import Resize from 'react-resize-detector';

class D3Chart extends Component {

  constructor(props) {
    super(props);

    this.state = {
      width: 500,
      height: 250
    };
  }

  componentDidMount() {
    this.handelResize(this.refs.wrapper.offsetWidth)
  }

  handelResize(width = 500, height = 250) {
    this.setState({width: width, height: height});
  }

  render() {
    return (
      <div ref="wrapper" height={this.state.height}>
        <Resize handleWidth onResize={this.handelResize.bind(this)}/>
        <svg ref="svg" width={this.state.width} height={this.state.height}></svg>
      </div>
    );
  }
}

export default D3Chart;