【问题标题】:Dygraphs in ReactReact 中的 Dygraphs
【发布时间】:2020-05-13 20:06:39
【问题描述】:

我正在尝试在我的 Reactjs Web 应用程序中使用 Dygraph,但我无法实现它。我对 Dygraphs 完全陌生。我尝试了这个演示图,但无法做到。网站还提供了有关基于 HTML 和 JS 的图表的详细信息。我在将它集成到我的 React 应用程序中时遇到了问题。另外,我不知道如何将数据传递给图表。请帮助解决这个问题。感谢您的帮助!

import React, { Component } from 'react';
import Dygraph from 'dygraphs';
import 'dygraphs/dist/dygraph.min.css'

class DyGraph extends Component {

constructor(props) {
    super(props);

    const g = new Dygraph('graph',
        `Date,A,B
    2016/01/01,10,20
    2016/07/01,20,10
    2016/12/31,40,30
    `, {
        title: 'Pressure Transient(s)',
        titleHeight: 32,
        ylabel: 'Pressure (meters)',
        xlabel: 'Time',
        gridLineWidth: '0.1',
        width: 700,
        height: 300,
        connectSeparatedPoints: true,
        axes: { "x": { "axisLabelFontSize": 9 }, "y": { "axisLabelFontSize": 9 } },
        labels: ['Date', 'Tampines Ave10 (Stn 40)'],

    });
}

render() {
    return <div id="graph"></div>;
}
}

export default DyGraph;

我收到以下错误:

Error: Constructing dygraph with a non-existent div!
▶ 2 stack frames were collapsed.
new DyGraph
D:/themesdemo/src/components/DyGraph/index.js:17
14 |        //     { name: 'Group D', value: 200 },
15 |        // ];
16 | 
> 17 |        const g = new Dygraph('graph',
   | ^  18 |            `Date,A,B
19 |        2016/01/01,10,20
20 |        2016/07/01,20,10

【问题讨论】:

    标签: javascript reactjs react-redux dygraphs


    【解决方案1】:

    问题是在组件挂载之前&lt;div&gt; 不存在于 DOM 中(顺序是constructor 然后render 然后componentDidMount)。如果您尝试在componentDidMount 中创建图表,您的运气会更好:

    class DyGraph extends Component {
      constructor(props) {
        super(props);
      }
    
      render() {
        return <div id="graph"></div>;
      }
    
      componentDidMount() {
        const g = new Dygraph('graph', `...`, { /* ... */ });
      }
    }
    

    如果页面上有多个图表,则需要使用ref

    还有一个react-dygraphs 库你可以试试,虽然它已经几年没有更新了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多