SoFunction
Updated on 2025-03-10

React implements the pop-up box component that dynamically calls

Recently, I am using react to develop a project and encountered a requirement - developing a pop-up component. Creating a component in react is very simple. You just need to use class to create and introduce it. However, in order to use js to call this component instead of writing it in the jsx structure, you need to use this method.

First of all, let’s take a lot of demands:

1. Configurable fields in the pop-up box: title text, prompt text, confirm and cancel button display hidden and text.
2. After clicking the confirm and cancel buttons, the corresponding event can be triggered.
3. Is it a short prompt? When the short prompt, the confirmation and cancel buttons are hidden and disappear after 2 seconds.

Next, use two methods to create a pop-up component and compare the differences between the two.

Let’s first implement a normal component written in the jsx structure:

Broadcast component:

import React, { Component } from 'react';
import './';
 
class DialogAlert extends Component {
    constructor(props){
        super(props);
         = {
            alertStatus:false,
            alertTitle:'hint', //title            alertTip:'Network Error', //hint            cancelText:'Cancel',
            confirmText:'confirm',
 
            isShortTip:false, //Is it a short prompt? In the case of a short prompt, "Cancel" and "confirm" will not be displayed (and disappears after 2s), and the priority is the highest, and other configurations are invalid 
            isShowCancel:true, //Whether to display the confirmation button            isShowConfirm:true, //Whether to display the confirmation button 
            cancelCallbackFn:function(){}, //Cancel callback function            confirmCallbackFn:function (){}//Confirm the callback function        }
    }
 
    componentWillReceiveProps(nextProps) {
        let options =  || {};
 
        //If it's a short prompt        if(){
             = false;
             = false;
            setTimeout(()=>{
                ()
            },2000)
        }
 
        ({
            ...options
        })
    }
 
    //Cancel    cancel = () => {
        ();
        ()
    }
    //confirm    confirm = () => {
        ();
        ()
    }
    close = () => {
        ({
            alertStatus:false
        })
    }
 
    render(){
        let opts = ;
        return (
            <div className="dialog-wrap" style={ ? {display:'block'}:{display:'none'}}>
                <div className="dialog-box">
                    <h6>{}</h6>
                    <p>{}</p>
                    {! && ! ? null : (
                        <div>
                            { ? (<span onClick={ () => () }>{}</span>) : null}
                            { ? (<span className="confirm" onClick={ () => () }>{}</span>) : null}
                        </div>
                        )}
                </div>
            </div>
        )
    }
}
 
export default DialogAlert;

The data update here uses the life cycle of componentWillReceiveProps. It is executed when props change, and it is not executed when initializing render. In this callback function, you can call() to update your component state according to the changes in the properties. Old properties can still be obtained through it. It is safe to call update status here and will not trigger additional render calls.

Call the page

Define variables for configurable fields in state

import DialogAlert from '../../widget/DialogAlert/index';
 
//The component's js is omitted 
 = {
    dialogOpt:{
        alertStatus:false,
        alertTip:'I'm custom content',
        cancelText:'Cancel 2',
        confirmText:'Confirm 2',
        isShortTip:false,
        isShowCancel:true, //Whether to display the confirmation button        isShowConfirm:true, //Whether to display the confirmation button        cancelCallbackFn:function(){
          alert(0);
        }, //Cancel callback function        confirmCallbackFn:function (){
          alert(1);
        }//Confirm the callback function      },
      //Other data    };

Build the corresponding component structure in jsx

<div onClick={()=>(())}>Click to trigger the pop-up box</div>
<DialogAlert dialogOpt={}></DialogAlert>

Add a trigger event

alertdialog(){
    let opts = {
      alertStatus:true
    }
    let _dialogOpt = (,opts)
    ({
      dialogOpt:_dialogOpt
    })
  }

This completes an ordinary pop-up frame. I always feel that the pop-up frame of a component written in this way is a bit redundant and it is also troublesome to reuse - configure all custom variables in the state and change the jsx structure, and you also need to pay attention to the hierarchy of the pop-up frame when writing the jsx structure.

Next, let's implement a dynamically invoked component:

The principle is to create a div and insert it into the body, use this div as a container, use render to render the component, and control the display and hiding of the component by changing the component's state.

Broadcast component:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './';
 
//Calling method// ({
    // alertTitle:'tip 2',    // alertTip: "The page failed to load, is it reloaded?",    // cancelText:'Cancel',    // confirmText:'Reload',    // isShortTip:true,
    // isShowCancel:true,
    // isShowConfirm:true,
    // cancelCallbackFn:function(){
    //   ('Cancelled')    // },
    // confirmCallbackFn:function (){
    // ("Confirmed...");    // }
// });
 
class DialogBox extends Component {
    constructor(props){
        super(props);
         = {
            alertStatus: false, //Whether the prompt box is displayed 
            alertTitle:'hint', //title            alertTip:'Network Error', //hint            cancelText:'Cancel',
            confirmText:'confirm',
 
            isShortTip:false, //Is it a short prompt? In the case of a short prompt, "Cancel" and "confirm" will not be displayed (and disappears after 2s), and the priority is the highest, and other configurations are invalid 
            isShowCancel:true, //Whether to display the confirmation button            isShowConfirm:true, //Whether to display the confirmation button 
            cancelCallbackFn:function(){}, //Cancel callback function            confirmCallbackFn:function (){}//Confirm the callback function        }
    }
 
    //Open the prompt box    open = (options) => {
        options = options || {};
        
        //If it's a short prompt        if(){
             = false;
             = false;
            setTimeout(()=>{
                ()
            },2000)
        }
 
         = true;
        ({
            ...options
        })
    }
    //Cancel    cancel = () => {
        ();
        ()
    }
    //confirm    confirm = () => {
        ();
        ()
    }
    close = () => {
        ({
            alertStatus:false
        })
    }
 
    render(){
        let opts = ;
        return (
            <div className="dialog-wrap" style={? {display:'block'}:{display:'none'}}>
                <div className="dialog-box">
                    <h6>{}</h6>
                    <p>{}</p>
                    {! && ! ? null : (
                        <div>
                            { ? (<span onClick={ () => () }>{}</span>) : null}
                            { ? (<span className="confirm" onClick={ () => () }>{}</span>) : null}
                        </div>
                        )}
                </div>
            </div>
        )
    }
}
 
let div = ('div');
(div);
let DialogAlert = (<DialogBox /> ,div); //Return the instance 
export default DialogAlert;

Call the page

import DialogAlert from '../../widget/DialogAlert/index';
   
//The component's js is omitted 
({
    alertTip:"Loading failed, did you reload?",
    confirmText:'Reload',
    cancelCallbackFn:()=>{
        ();
    },
    confirmCallbackFn:()=>{
        //todo...
    }
})

This is used here. The official document says that this method will currently return a reference to the root component instance, so we can call the open method inside. However, the use of returned references should be avoided in the official documentation, as it is a historical legacy.In order to be compatible with the iteration of react updates in the future, we can omit the process of dynamically inserting the component, write it in jsx instead, and set the ref, using the instance of the current component to call the instance method.

Just introduce it and call it directly. The advantage of writing this way is that it solves the hierarchy of the pop-up frame, and there is no need to change the jsx structure, making it more convenient and quick to reuse other pages.

The two methods are not very different in the definition of components, but there are differences when updating the state. The first method is to listen to the changes in the value of the parent component during the life cycle of componentWillReceiveProps and then update it to the state. The second method is to directly call the open method of the instance to update the value to the state by obtaining parameters.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.