index.jsx 691 B

1234567891011121314151617181920212223242526272829
  1. import React, { Component } from 'react';
  2. import ReactDOM from 'react-dom';
  3. //传送门,将dom渲染到body节点
  4. class NewPortal extends Component {
  5. constructor(props) {
  6. super(props)
  7. // 初始化创建渲染的父元素并添加到body下
  8. this.node = document.createElement('div');
  9. }
  10. componentDidMount() {
  11. document.body.appendChild(this.node);
  12. }
  13. componentWillUnmount() {
  14. document.body.removeChild(this.node);
  15. }
  16. render() {
  17. const { visible,children } = this.props;
  18. return visible && ReactDOM.createPortal(
  19. children,
  20. this.node
  21. )
  22. }
  23. }
  24. export default NewPortal;