zent
Version:
一套前端设计语言和基于React的实现
69 lines (68 loc) • 2.31 kB
JavaScript
import { __assign, __extends } from "tslib";
import { jsx as _jsx } from "react/jsx-runtime";
import { Component } from 'react';
import { createPortal } from 'react-dom';
import memoize from '../utils/memorize-one';
import { getNodeFromSelector, removeAllChildren } from './util';
import { PortalContext } from './context';
var PurePortal = (function (_super) {
__extends(PurePortal, _super);
function PurePortal() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.childContext = {
children: [],
};
_this.getContainer = memoize(function (selector) {
var node = getNodeFromSelector(selector);
if (!node) {
return node;
}
if (!_this.props.append) {
removeAllChildren(node);
}
return node;
});
return _this;
}
PurePortal.prototype.contains = function (el) {
var container = this.getContainer(this.props.selector);
if (!container) {
return false;
}
if (container.contains(el)) {
return true;
}
for (var _i = 0, _a = this.childContext.children; _i < _a.length; _i++) {
var child = _a[_i];
if (child.contains(el)) {
return true;
}
}
return false;
};
PurePortal.prototype.componentDidMount = function () {
this.context.children.push(this);
};
PurePortal.prototype.componentWillUnmount = function () {
var index = this.context.children.indexOf(this);
if (index !== -1) {
this.context.children.splice(index, 1);
}
};
PurePortal.prototype.render = function () {
var container = this.props.selector;
var children = this.props.children;
var domNode = this.getContainer(container);
if (!domNode) {
return null;
}
return createPortal(_jsx(PortalContext.Provider, __assign({ value: this.childContext }, { children: children }), void 0), domNode);
};
PurePortal.defaultProps = {
append: false,
};
PurePortal.contextType = PortalContext;
return PurePortal;
}(Component));
export { PurePortal };
export default PurePortal;