React 中的 Dygraphs

Dygraphs in React

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

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

问题是 <div> 在组件安装后才存在于 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 库你可以试试,虽然它已经几年没有更新了。