我试图在我的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
问题是 <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', `...`, { /* ... */ });
}
}
如果你的页面上有多个图表,你就需要使用一个 档号.
还有一个 react-dygraphs
库你可以试试,虽然它已经有几年没有更新了。