React programmatic popup

foreword

React's current mainstream Antd library is actually pretty easy to use, but some custom things still need to be written by yourself.
At the same time, let’s criticize the current blog articles, which are good and bad. The garbage is dead, and many things are so bad that they can’t be worse. What are they writing.

Not much to say, just paste the code directly
(write the CSS style yourself)

import React from "react-dom";
import ReactDOM from "react-dom";

const Element = () => {
    
    
    return <div style={
    
    {
    
     width: '400px;', height: '500px', background: "red" }}>
        <button onClick={
    
    GlobalElement.destroy}>关闭</button>
    </div>
}

const ELEMENT_ID: string = "test-dom"

const GlobalElement = {
    
    
  install: () => {
    
    
    // 在body里面创建一个dom,同时挂载,然后通过React.render去挂载渲染对应的jsx node
    // 其实和vue的 Vue.mount函数没有区别,用法思路是一样的
    if (!React.findDOMNode(document.getElementById(ELEMENT_ID))) {
    
    
      const element: HTMLDivElement = document.createElement("div");
      element.id = ELEMENT_ID
      document.body.appendChild(element)
      React.render(<Element/>, element)
    }
  },
  destroy: () => {
    
    
    const targetDOM = document.getElementById(ELEMENT_ID) as HTMLElement
    const unmountResult = ReactDOM.unmountComponentAtNode(targetDOM);
    if (unmountResult) {
    
    
        document.body.removeChild(targetDOM)
    }
  }
}

export default LoginGlobalElement


You know how to use it yourself. If you don’t know how to use it, I suggest you give up React or relearn React.
This writing method is similar to Vue’s. It creates an empty Dom element, mounts Dom on the body, and then The JSXElement that needs to be rendered is rendered into the newly created Dom.

Guess you like

Origin blog.csdn.net/qq_16733389/article/details/131250566