React弹出层组件一

react正常无法在父组件dom节点之外的其他节点创建组件,查文档发现react提供了Portals方法来实现:

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

文档地址:传送门

示例代码:

import React from 'react'
import ReactDOM from 'react-dom'

export default class Layer extends React.Component {
    constructor(props) {
        super(props);
        this.el = document.createElement('div');
        this.el.setAttribute('class', 'layer');
    }
    componentDidMount() {
        document.body.appendChild(this.el);
    }
    componentWillUnmount() {
        document.body.removeChild(this.el);
    }
    render() {
        return ReactDOM.createPortal((
            
layer
), this.el); } }
React弹出层组件一_第1张图片
layer.png

你可能感兴趣的:(React弹出层组件一)