index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import React, { PureComponent } from 'react';
  2. import G2 from 'g2';
  3. import equal from '../equal';
  4. import styles from '../index.less';
  5. class MiniArea extends PureComponent {
  6. static defaultProps = {
  7. borderColor: '#1890FF',
  8. color: 'rgba(24, 144, 255, 0.2)',
  9. };
  10. componentDidMount() {
  11. this.renderChart(this.props.data);
  12. }
  13. componentWillReceiveProps(nextProps) {
  14. if (!equal(this.props, nextProps)) {
  15. this.renderChart(nextProps.data);
  16. }
  17. }
  18. componentWillUnmount() {
  19. if (this.chart) {
  20. this.chart.destroy();
  21. }
  22. }
  23. handleRef = (n) => {
  24. this.node = n;
  25. }
  26. renderChart(data) {
  27. const {
  28. height = 0, fit = true, color, borderWidth = 2, line, xAxis, yAxis, animate = true,
  29. } = this.props;
  30. const borderColor = this.props.borderColor || color;
  31. if (!data || (data && data.length < 1)) {
  32. return;
  33. }
  34. // clean
  35. this.node.innerHTML = '';
  36. const chart = new G2.Chart({
  37. container: this.node,
  38. forceFit: fit,
  39. height: height + 54,
  40. animate,
  41. plotCfg: {
  42. margin: [36, 5, 30, 5],
  43. },
  44. legend: null,
  45. });
  46. if (!xAxis && !yAxis) {
  47. chart.axis(false);
  48. }
  49. if (xAxis) {
  50. chart.axis('x', xAxis);
  51. } else {
  52. chart.axis('x', false);
  53. }
  54. if (yAxis) {
  55. chart.axis('y', yAxis);
  56. } else {
  57. chart.axis('y', false);
  58. }
  59. const dataConfig = {
  60. x: {
  61. type: 'cat',
  62. range: [0, 1],
  63. ...xAxis,
  64. },
  65. y: {
  66. min: 0,
  67. ...yAxis,
  68. },
  69. };
  70. chart.tooltip({
  71. title: null,
  72. crosshairs: false,
  73. map: {
  74. title: null,
  75. name: 'x',
  76. value: 'y',
  77. },
  78. });
  79. const view = chart.createView();
  80. view.source(data, dataConfig);
  81. view.area().position('x*y').color(color).shape('smooth')
  82. .style({ fillOpacity: 1 });
  83. if (line) {
  84. const view2 = chart.createView();
  85. view2.source(data, dataConfig);
  86. view2.line().position('x*y').color(borderColor).size(borderWidth)
  87. .shape('smooth');
  88. view2.tooltip(false);
  89. }
  90. chart.render();
  91. this.chart = chart;
  92. }
  93. render() {
  94. const { height } = this.props;
  95. return (
  96. <div className={styles.miniChart} style={{ height }}>
  97. <div className={styles.chartContent}>
  98. <div ref={this.handleRef} />
  99. </div>
  100. </div>
  101. );
  102. }
  103. }
  104. export default MiniArea;