SlideWrap.tsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import React from 'react';
  2. import { createPortal } from 'react-dom';
  3. import styled from 'styled-components';
  4. const Container = styled.div`
  5. position: fixed;
  6. top: 0;
  7. left: 0;
  8. width: 100%;
  9. height: 100%;
  10. z-index: 2000;
  11. overflow: hidden;
  12. `;
  13. export default class SlideWrap extends React.Component<{
  14. className?: string;
  15. children: any;
  16. }> {
  17. static displayName = 'SlideWrap';
  18. private dialogNode;
  19. private originalOverflow;
  20. constructor(props) {
  21. super(props);
  22. // 创建容器
  23. this.dialogNode = document.createElement('section');
  24. document.body.appendChild(this.dialogNode);
  25. }
  26. componentDidMount() {
  27. this.preventScroll();
  28. }
  29. componentWillUnmount() {
  30. this.allowScroll();
  31. // 清除容器
  32. document.body.removeChild(this.dialogNode);
  33. this.dialogNode = undefined;
  34. }
  35. preventScroll = () => {
  36. const { style } = document.body;
  37. this.originalOverflow = style.overflow;
  38. style.overflow = 'hidden';
  39. }
  40. allowScroll = () => {
  41. const { style } = document.body;
  42. style.overflow = this.originalOverflow;
  43. this.originalOverflow = undefined;
  44. }
  45. render() {
  46. const { className, children } = this.props;
  47. return createPortal(
  48. <Container className={className}>
  49. {children}
  50. </Container>,
  51. this.dialogNode,
  52. );
  53. }
  54. }