UNPKG

lm-portal

Version:

* 作者:David Feng * 邮箱:sublime3@163.com * 版本:**`0.2.0`**

90 lines (73 loc) 1.79 kB
/** * Created by David Feng<sublime3@163.com>. * ComponentName Portal * Desc 任意组件传送门 * GroupName lm-component */ import React, { Component } from 'react' import ReactDOM from 'react-dom' import PropTypes from 'prop-types' /** * @class Portal * @extends React.Component * @desc Portal Component for mobile */ export default class Portal extends Component { static propTypes = { /* * 被插入节点 */ children: PropTypes.element.isRequired, /* * 目标插入参数 */ target: PropTypes.any.isRequired, /* * 是否每次更新都始终执行 append 被废弃的api */ alwaysAppend: PropTypes.bool, /* * 外层容器 class 名 */ className: PropTypes.string }; static defaultProps = { target: document.body, alwaysAppend: true }; /** * @constructor */ constructor(props) { super(props); const { className } = this.props; this.wrapper = document.createElement('div'); if (className) { this.wrapper.className = className; } } componentDidMount() { this.mountChild(this.props.target); } componentWillUnmount() { this.unmountChild(); } mountChild(target) { this.targetNode = ReactDOM.findDOMNode(target); this.targetNode.appendChild(this.wrapper); } unmountChild() { if (this.targetNode) { this.targetNode.removeChild(this.wrapper); this.targetNode = null; } } render () { return ReactDOM.createPortal( this.props.children, this.wrapper ) } }