autoHeight.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* eslint eqeqeq: 0 */
  2. import React from 'react';
  3. function computeHeight(node) {
  4. const totalHeight = parseInt(getComputedStyle(node).height, 10);
  5. const padding =
  6. parseInt(getComputedStyle(node).paddingTop, 10) +
  7. parseInt(getComputedStyle(node).paddingBottom, 10);
  8. return totalHeight - padding;
  9. }
  10. function getAutoHeight(n) {
  11. if (!n) {
  12. return 0;
  13. }
  14. let node = n;
  15. let height = computeHeight(node);
  16. while (!height) {
  17. node = node.parentNode;
  18. if (node) {
  19. height = computeHeight(node);
  20. } else {
  21. break;
  22. }
  23. }
  24. return height;
  25. }
  26. const autoHeight = () => (WrappedComponent) => {
  27. return class extends React.Component {
  28. state = {
  29. computedHeight: 0,
  30. };
  31. componentDidMount() {
  32. const { height } = this.props;
  33. if (!height) {
  34. const h = getAutoHeight(this.root);
  35. // eslint-disable-next-line
  36. this.setState({ computedHeight: h });
  37. }
  38. }
  39. handleRoot = (node) => {
  40. this.root = node;
  41. };
  42. render() {
  43. const { height } = this.props;
  44. const { computedHeight } = this.state;
  45. const h = height || computedHeight;
  46. return (
  47. <div ref={this.handleRoot}>{h > 0 && <WrappedComponent {...this.props} height={h} />}</div>
  48. );
  49. }
  50. };
  51. };
  52. export default autoHeight;