index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import React, { PureComponent } from 'react';
  2. import G2 from 'g2';
  3. import equal from '../equal';
  4. import styles from '../index.less';
  5. class MiniBar extends PureComponent {
  6. componentDidMount() {
  7. this.renderChart(this.props.data);
  8. }
  9. componentWillReceiveProps(nextProps) {
  10. if (!equal(this.props, nextProps)) {
  11. this.renderChart(nextProps.data);
  12. }
  13. }
  14. componentWillUnmount() {
  15. if (this.chart) {
  16. this.chart.destroy();
  17. }
  18. }
  19. handleRef = (n) => {
  20. this.node = n;
  21. }
  22. renderChart(data) {
  23. const { height = 0, fit = true, color = '#1890FF' } = this.props;
  24. if (!data || (data && data.length < 1)) {
  25. return;
  26. }
  27. // clean
  28. this.node.innerHTML = '';
  29. const { Frame } = G2;
  30. const frame = new Frame(data);
  31. const chart = new G2.Chart({
  32. container: this.node,
  33. forceFit: fit,
  34. height: height + 54,
  35. plotCfg: {
  36. margin: [36, 5, 30, 5],
  37. },
  38. legend: null,
  39. });
  40. chart.axis(false);
  41. chart.source(frame, {
  42. x: {
  43. type: 'cat',
  44. },
  45. y: {
  46. min: 0,
  47. },
  48. });
  49. chart.tooltip({
  50. title: null,
  51. crosshairs: false,
  52. map: {
  53. name: 'x',
  54. },
  55. });
  56. chart.interval().position('x*y').color(color);
  57. chart.render();
  58. this.chart = chart;
  59. }
  60. render() {
  61. const { height } = this.props;
  62. return (
  63. <div className={styles.miniChart} style={{ height }}>
  64. <div className={styles.chartContent}>
  65. <div ref={this.handleRef} />
  66. </div>
  67. </div>
  68. );
  69. }
  70. }
  71. export default MiniBar;