Protal提供了一种将子节点渲染到存在于父组件以外的DOM节点的优秀的方案
1.第一个参数(child)是任何可渲染的React子元素,例如一个元素,字符串fragment
2.第二个参数(container)是一个DOM元素
因为我们渲染的内容默认都是挂载到组件父级节点,最根也只是id为root的DOM节点上的,当我们渲染的这个元素要脱离root时可以通过ReactDOM.createPortal来实现
Test1.jsx //父组件
import React, {PureComponent } from 'react';
import Modal from "./component/Modal/index";
export default class Test1 extends PureComponent {
state = {
showModal : false
}
onCancel(){
this.setState({
showModal: false
})
}
render() {
return (
<div>
<button onClick={()=>this.setState({showModal: true})}>弹出Modal</button>
<Modal show={this.state.showModal} onCancel={()=>this.onCancel()}>
<div style={{width: '100px', height: '100px', background: '#ffffff'}}>
Modal-view
</div>
</Modal>
</div>
);
}
}
Modal/index.jsx // Modal组件
import React, {Component} from 'react';
import ReactDOM from 'react-dom'
import './index.css'
export default class Modal extends Component {
state = {
aniClass: ''
}
render() {
const {show=false,onCancel} = this.props
return show ? ReactDOM.createPortal(
<div className='modal-view'>
<div className='close-btn' onClick={onCancel}>关闭</div>
{this.props.children}
</div>,
document.body
) : null
}
}
Modal/index.css //Modal组件样式
.modal-view{
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.6);
position: fixed;
left: 0;
top: 0;
display: flex;
align-items: center;
justify-content: center;
}
.modal-view .close-btn{
position: absolute;
right: 10px;
top: 10px;
background: #ffffff;
cursor: pointer;
}
可以看到节点被挂载在body
评论