开局先挂官方文档
https://react.docschina.org/docs/portals.html
实现全局弹出层 App.jsimport React from 'react';
import './App.css';
import Mask from './Portals/Mask'
class App extends React.Component {
constructor(props){
super(props);
this.state = {
showMask:true
}
this.handler = this.handler.bind(this);
}
handler(){
let showMask = this.state.showMask;
this.setState({showMask:!showMask});
}
render() {
let showMask = this.state.showMask;
let mask = showMask ?
hidden
: null;
return (
show
{mask}
);
}
}
export default App;
App.css
.modal {
color: #fff;
background-color: rgba(0, 0, 0, 1);
position: fixed;
top: 0;
left: 0;
z-index: 999;
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
Mask.jsx
import React,{Component} from 'react'
import ReactDOM from 'react-dom'
const root = document.getElementById('root');
export default class Mask extends Component{
constructor(props){
super(props)
this.state={
}
this.el = document.createElement('div');
}
componentDidMount(){
root.appendChild(this.el);
}
componentWillUnmount(){
root.removeChild(this.el);
}
render (){
return ReactDOM.createPortal(
this.props.children,
this.el
);
}
}
我们先看下Portals文档
ReactDOM.createPortal(child, container) 第一个参数(child)是任何可渲染的 React 子元素,例如一个元素,字符串或 fragment。 第二个参数(container)是一个 DOM 元素。
简单的理解就是,你写一个组件,将组件的内容用Portal挂载在跟节点id=root的节点,他就是全局的了
改造一下,使用起来更加方便 App.jsimport React from 'react';
import './App.css';
import Mask from './Portals/Mask'
class App extends React.Component {
constructor(props){
super(props);
this.state = {
showMask:false
}
this.onHandler = this.onHandler.bind(this)
}
onHandler(){
let showMask = this.state.showMask;
this.setState({showMask:!showMask});
}
render() {
return (
show
);
}
}
export default App;
App.css
同上
Mask.jsximport React,{Component} from 'react'
import ReactDOM from 'react-dom'
const root = document.getElementById('root');
export default class Mask extends Component{
constructor(props){
super(props)
this.state={
}
this.el = document.createElement('div');
}
componentDidMount(){
root.appendChild(this.el);
}
componentWillUnmount(){
root.removeChild(this.el);
}
render (){
return ReactDOM.createPortal(
this.props.showMask ?
this.props.onHandler()}>hidden
: null,
this.el
);
}
}