REACT-portal将组件渲染到指定的父组件外部节点
Portal 提供了一个最好的在父组件包含的DOM结构层级外的DOM节点渲染组件的方法。
1. App.js+App.css
import './App.css'
import React, { Component } from 'react'
import PortalDialog from './components/PortalDialog'
export default class App extends Component {
state = {
show:false
}
render() {
return (
<div className='box'>
<div className='left'></div>
<div className='right'>
<button onClick={()=>{
this.setState({show:true})
}}>打开dialog</button>
{
this.state.show
&&
<PortalDialog onClose={()=>{
this.setState({show:false})
}}>
<div>11111111</div>
<div>22222222</div>
<div>33333333</div>
</PortalDialog>
}
</div>
</div>
)
}
}
*{
margin: 0;;
padding: 0;
}
.box{
display: flex;
}
.left,.right{
height: 100vh;
}
.left{
width: 200px;
background-color: yellow;
}
.right{
flex: 1;
background-color: pink;
}
2. components/PortalDialog.js
import React, { Component } from 'react'
import { createPortal } from 'react-dom'
export default class PortalDialog extends Component {
render() {
return createPortal(
<div style={{width:'100%',height:'100%',position:'fixed',left:0,top:0,background:'rgb(0,0,0,0.7)',color:'white'}}>
{this.props.children}
<button onClick={this.props.onClose}>关闭dialog</button>
</div>,
document.body
)
}
}