我试图美化当数据更改时作为React组件编写的C3图表的更新。数据通过其道具从父组件流到该组件。
我现在拥有的解决方案“有效”,但似乎不是最佳方案:输入新数据后,将重新生成整个图表。我想过渡到新状态(线条移动而不是整个图表在瞬间更新)。C3 API似乎有很多方法,但是我找不到如何到达图表。
var React = require("react");
var c3 = require("c3");
var ChartDailyRev = React.createClass({
_renderChart: function (data) {
var chart = c3.generate({
bindto: '#chart1',
data: {
json: data,
keys: {
x: 'date',
value: ['requests', 'revenue']
},
type: 'spline',
types: { 'revenue': 'bar' },
axes: {
'requests': 'y',
'revenue': 'y2'
}
},
axis: {
x: { type: 'timeseries' },
y2: { show: true }
}
});
},
componentDidMount: function () {
this._renderChart(this.props.data);
},
render: function () {
this._renderChart(this.props.data);
return (
<div className="row" id="chart1"></div>
)
}
});
module.exports = ChartDailyRev;
根据项目的文档:
通过使用API,您可以在渲染图表后对其进行更新。...可以通过从返回的对象来调用API
generate()
。
因此,您需要做的第一件事就是在生成图表时保存对图表的引用。将它直接附加到组件很容易:
var ChartDailyRev = React.createClass({
_renderChart: function (data) {
// save reference to our chart to the instance
this.chart = c3.generate({
bindto: '#chart1',
// ...
});
},
componentDidMount: function () {
this._renderChart(this.props.data);
},
// ...
});
然后,您要在道具更新时更新图表;React提供了一个称为生命周期的钩子componentWillReceiveProps
,该钩子会在道具发生变化时运行。
var ChartDailyRev = React.createClass({
// ...
componentWillReceiveProps: function (newProps) {
this.chart.load({
json: newProps.data
}); // or whatever API you need
}
});
(确保this._renderChart
从render
功能中删除。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句