您当前的位置: 首页 > 

【03】

暂无认证

  • 0浏览

    0关注

    196博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Portal的使用-全局组件的实现

【03】 发布时间:2020-08-19 09:01:59 ,浏览量:0

开局先挂官方文档

https://react.docschina.org/docs/portals.html

实现全局弹出层 App.js
import 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.js
import 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.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.showMask ?
        
          this.props.onHandler()}>hidden
         : null,
        this.el
      );
    }
}
关注
打赏
1657344724
查看更多评论
立即登录/注册

微信扫码登录

0.0485s