index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import React, { Component } from 'react';
  2. import { Chart, Axis, Tooltip, Geom } from 'bizcharts';
  3. import Debounce from 'lodash-decorators/debounce';
  4. import Bind from 'lodash-decorators/bind';
  5. import autoHeight from '../autoHeight';
  6. import styles from '../index.less';
  7. @autoHeight()
  8. class Bar extends Component {
  9. state = {
  10. autoHideXLabels: false,
  11. };
  12. componentDidMount() {
  13. window.addEventListener('resize', this.resize);
  14. }
  15. componentWillUnmount() {
  16. window.removeEventListener('resize', this.resize);
  17. }
  18. @Bind()
  19. @Debounce(400)
  20. resize() {
  21. if (!this.node) {
  22. return;
  23. }
  24. requestAnimationFrame(() => {
  25. const canvasWidth = this.node.parentNode.clientWidth;
  26. const { data = [], autoLabel = true } = this.props;
  27. if (!autoLabel) {
  28. return;
  29. }
  30. const minWidth = data.length * 30;
  31. const { autoHideXLabels } = this.state;
  32. if (canvasWidth <= minWidth) {
  33. if (!autoHideXLabels) {
  34. this.setState({
  35. autoHideXLabels: true,
  36. });
  37. }
  38. } else if (autoHideXLabels) {
  39. this.setState({
  40. autoHideXLabels: false,
  41. });
  42. }
  43. });
  44. }
  45. handleRoot = n => {
  46. this.root = n;
  47. };
  48. handleRef = n => {
  49. this.node = n;
  50. };
  51. render() {
  52. const {
  53. height,
  54. title,
  55. forceFit = true,
  56. data,
  57. color = 'rgba(24, 144, 255, 0.85)',
  58. padding,
  59. } = this.props;
  60. const { autoHideXLabels } = this.state;
  61. const scale = {
  62. x: {
  63. type: 'cat',
  64. },
  65. y: {
  66. min: 0,
  67. },
  68. };
  69. const tooltip = [
  70. 'x*y',
  71. (x, y) => ({
  72. name: x,
  73. value: y,
  74. }),
  75. ];
  76. return (
  77. <div className={styles.chart} style={{ height }} ref={this.handleRoot}>
  78. <div ref={this.handleRef}>
  79. {title && <h4 style={{ marginBottom: 20 }}>{title}</h4>}
  80. <Chart
  81. scale={scale}
  82. height={title ? height - 41 : height}
  83. forceFit={forceFit}
  84. data={data}
  85. padding={padding || 'auto'}
  86. >
  87. <Axis
  88. name="x"
  89. title={false}
  90. label={autoHideXLabels ? false : {}}
  91. tickLine={autoHideXLabels ? false : {}}
  92. />
  93. <Axis name="y" min={0} />
  94. <Tooltip showTitle={false} crosshairs={false} />
  95. <Geom type="interval" position="x*y" color={color} tooltip={tooltip} />
  96. </Chart>
  97. </div>
  98. </div>
  99. );
  100. }
  101. }
  102. export default Bar;