javascript - 在 React 中将 D3 图表调整为父级

标签 javascript d3.js reactjs

我正在学习来自:http://ahmadchatha.com/writings/article1.html 的教程

它会像这样设置一个 React 组件:

class SimplePie extends React.Component {
  render() {
    return (
      <div className="col-xs-4 chart"
        style={{background: this.props.data[1]}} >
        {this.props.title}
        <D3Chart
          width={200}
          height={200}>
          <DataSeries
            data={this.props.data[0]}
            colors={colors}
            width={200} height={200} />
        </D3Chart>
      </div>
    )
  }
}

但我想更改此设置,以便 D3Chart 将根据父级的大小调整大小,并监听调整大小事件。在 React 中有什么简单的方法可以做到这一点吗?

我正在努力使用事件监听器来调整特定 div 上的事件大小。

最佳答案

用 React 测量元素的大小并不像您想象的那么简单,主要原因是 React 并不真正关心大小,您必须在绘制后从 DOM 中读取它们。

对于您这里的情况,我们可以在窗口 元素,像这样:

class SimplePie extends React.Component {
  constructor (props, context) {
    super(props, context);
    this.state = {
           width: 200,
           height: 200
        };
    this.measure = this.measure.bind(this);
  }
  componentWillMount () {
    window.addEventListener('resize', this.measure, false);
  }
  componentWillUnmount () {
    window.removeEventListener('resize', this.measure, false);
  }
  measure () {
    let rect = this.container.getBoundingClientRect();
    if(this.state.width !== rect.width || this.state.height !== rect.height){
       this.setState({
              width: rect.width, 
              height: rect.height
           });
    }
  }
  componentDidMount (){
     this.measure();
  }
  componentDidUpdate (){
     this.measure();
  }
  render() {
    return (
      <div ref={(container)=>{this.container = container}} style={{width: "100%", height: 300}} className="col-xs-4 chart"
        style={{background: this.props.data[1]}} >
        {this.props.title}
        <D3Chart
          width={this.state.width}
          height={this.state.height}>
          <DataSeries
            data={this.props.data[0]}
            colors={colors}
            width={this.state.width} height={this.state.height} />
        </D3Chart>
      </div>
    )
  }
}

编辑:容器必须有固定的宽度和高度,如果你想使用基于百分比的高度你必须设置这个组件的父级的高度。

关于javascript - 在 React 中将 D3 图表调整为父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39174159/

相关文章:

javascript - D3.js 在鼠标悬停时更改文本,这可能吗?

css - Material UI 将 Box 元素定位到父级底部

javascript - useEffect 在自定义钩子(Hook)中使用 ref 缺少依赖项警告

javascript - 是否可以在悬停 div 时从 .m3u 源流式传输?

javascript - 更新 d3 Force Layout 中的现有节点

javascript - 如何在 d3.js 中制作圆形图像

css - Draft.js 更改默认等宽字体

javascript - 滚动时透明导航栏可见

javascript - 文字不会出现在 IE8 及更低版本中

javascript - backbone.js - 模板不会在 asp.net View 上呈现