在react中写弹出层,警告框,tooltips等类似组件时,我们希望这些组件可以不依赖任何组件而独自存在。那么如何可以让这些组件在render的时候不存放在我们主组件中,而是单独存放在自己的dom中呢?代码如下
import React from 'react';
import ReactDOM from'react-dom';
import PropTypes from 'prop-types';
const createContainer = (DecoratorsComponent) => {
class Container extends React.Component {
constructor(props) {
super(props);
this.div = null;
}
static propTypes = {
visible: PropTypes.bool
}
static defaultProps = {
visible: false
}
removeMask = () => {
this.div && ReactDOM.unmountComponentAtNode(this.div);
document.body.removeChild(this.div);
this.div=null;
}
componentWillReceiveProps(nextProps) {
if (!this.div && nextProps.visible) {
this.div = document.createElement('div');
document.body.appendChild(this.div);
}
this.div && ReactDOM.render(
<DecoratorsComponent {...nextProps} removeMask={this.removeMask}>{nextProps.children}</DecoratorsComponent>, this.div);
}
render() {
return null;
}
}
return Container;
}
export default createContainer;
这个高阶组件的写法用到装饰者,如果不适应可以改用function形式