首页 web前端 前端问答 react怎么实现弹出模态框

react怎么实现弹出模态框

Jan 19, 2023 pm 03:43 PM
react

react实现弹出模态框的方法:1、用createPortal把元素直接渲染到“document.body”下;2、通过“modelShow”和“modelShowAync”来控制弹窗的显示隐藏;3、用一个控制器controlShow来流畅执行更新任务即可。

react怎么实现弹出模态框

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

react怎么实现弹出模态框?

react实现Modal弹窗

一、Dialog.js文件

import React, {useMemo, useEffect, useState} from 'react'
import ReactDOM from 'react-dom'
/**
 *
 * 需要把元素渲染到组件之外,用 createPortal 把元素直接渲染到 document.body 下,为了防止函数组件每一次执行都触发 createPortal, 所以通过 useMemo 做性能优化。
 因为需要渐变的动画效果,所以需要两个变量 modelShow / modelShowAync 来控制显示/隐藏,modelShow 让元素显示/隐藏,modelShowAync 控制动画执行。
 当弹窗要显示的时候,要先设置 modelShow 让组件显示,然后用 setTimeout 调度让 modelShowAync 触发执行动画。
 当弹窗要隐藏的时候,需要先让动画执行,所以先控制 modelShowAync ,然后通过控制 modelShow 元素隐藏,和上述流程相反。
 用一个控制器 controlShow 来流畅执行更新任务。
 */
// 控制弹窗隐藏以及动画效果
const controlShow = (f1, f2, value, timer) => {
    f1(value)
    return setTimeout(() => {
        f2(value)
    }, timer)
}
export const Dialog = (props) => {
    const {width, visible, closeCb, onClose} = props
    // 控制 modelShow动画效果
    const [modelShow, setModelShow] = useState(visible)
    const [modelShowAsync, setModelShowAsync] = useState(visible)
    const renderChildren = useMemo(() => {
        // 把元素渲染到组件之外的document.body 上
        return ReactDOM.createPortal(<div style={{display: modelShow ? &#39;block&#39; : &#39;none&#39;}}>
            <div className="model_container" style={{opacity: modelShowAsync ? 1 : 0}}>
                <div className="model_wrap">
                    <div style={{width: width + &#39;px&#39;}}> {props.children} </div>
                </div>
            </div>
            <div className="model_container mast" onClick={() => onClose && onClose()}
                 style={{opacity: modelShowAsync ? 0.6 : 0}}/>
        </div>, document.body)
    }, [modelShow, modelShowAsync])
    useEffect(() => {
        let timer
        if (visible) {
            // 打开弹窗,
            timer = controlShow(setModelShow, setModelShowAsync, visible, 30)
        } else {
            timer = controlShow(setModelShowAsync,setModelShow,visible,1000)
        }
        return () => {
            timer && clearTimeout(timer)
        }
    }, [visible])
    return renderChildren
}
登录后复制

二、Modal.js

import {Dialog} from "./Dialog";
import React, {useEffect, useState} from &#39;react&#39;
import ReactDOM from &#39;react-dom&#39;
import &#39;./style.scss&#39;
class Modal extends React.PureComponent {
    // 渲染底部按钮
    renderFooter = () => {
        const {onOk, onCancel, cancelText, okText, footer} = this.props
        //    触发onOk / onCancel回调
        if (footer && React.isValidElement(footer)) return footer
        return <div className="model_bottom">
            <div className="model_btn_box">
                <button className="searchbtn"
                        onClick={(e) => {
                            onOk && onOk(e)
                        }}>{okText || &#39;确定&#39;}
                </button>
                <button className="concellbtn"
                        onClick={(e) => {
                            onCancel && onCancel(e)
                        }}>{cancelText || &#39;取消&#39;}
                </button>
            </div>
        </div>
    }
    // 渲染底部
    renderTop = () => {
        const {title, onClose} = this.props
        return <div className="model_top">
            <p>{title}</p>
            <span className="model_top_close" onClick={() => onClose && onClose()}>X</span>
        </div>
    }
    // 渲染弹窗内容
    renderContent = () => {
        const {content, children} = this.props
        return React.isValidElement(content) ? content : children ? children : null
    }
    render() {
        const {visible, width = 500, closeCb, onClose} = this.props
        return <Dialog
            closeCb={closeCb}
            onClose={onClose}
            visible={visible}
            width={width}
        >
            {this.renderTop()}
            {this.renderContent()}
            {this.renderFooter()}
        </Dialog>
    }
}
// 静态方法
let ModalContainer = null
const modelSymbol = Symbol(&#39;$$_model_Container_hidden&#39;)
// 静态属性show——控制
Modal.show = (config) => {
    //  如果modal已经存在,name就不需要第二次show
    if (ModalContainer) return
    const props = {...config, visible: true}
    const container = ModalContainer = document.createElement(&#39;div&#39;)
    // 创建一个管理者,管理model状态
    const manager = container[modelSymbol] = {
        setShow: null,
        mounted: false,
        hidden() {
            const {setShow} = manager
            setShow && setShow(false)
        },
        destroy() {
            //    卸载组件
            ReactDOM.unmountComponentAtNode(container)
            // 移除节点
            document.body.removeChild(container)
            // 置空元素
            ModalContainer = null
        }
    }
    const ModelApp = (props) => {
        const [show, setShow] = useState(false)
        manager.setShow = setShow
        const {visible, ...trueProps} = props
        useEffect(() => {
            // 加载完成,设置状态
            manager.mounted = true
            setShow(visible)
        }, [])
        return <Modal {...trueProps} closeCb={() => manager.mounted && manager.destroy()} visible={show}/>
    }
    // 插入到body中
    document.appendChild(container)
    // 渲染React元素
    ReactDOM.render(<ModelApp/>, container)
    return manager
}
Modal.hidden = () => {
    if(!ModalContainer) return
    // 如果存在ModalContainer 那么隐藏ModalContainer
    ModalContainer[modelSymbol] && ModalContainer[modelSymbol].hidden()
}
export default Modal
登录后复制

三、style.scss样式文件

$bg-linear-gradien-red-light : linear-gradient(135deg, #fc4838 0%, #f6346b  100%);
$bg-linear-gradien-red-dark : linear-gradient(135deg, #fc4838 0%, #f6346b  100%);
.constrol{
  padding: 30px;
  width: 500px;
  border: 1px solid #ccc;
  height: 200px;
}
.feel{
  padding: 24px;
}
.model_top{
  height: 40px;
  border-radius: 5px  5px 0 0 ;
  position: relative;
  p{
    height: 40px;
    font-weight: bold;
    line-height: 40px;
    padding-left: 14px;
  }
  background-color: #eee;
  .model_top_close{
    position: absolute;
    font-size: 16px;
    cursor: pointer;
    right: 24px;
    top: 8px;
  }
}
.model_bottom{
  height: 50px;
  padding-top: 10px;
  .model_btn_box{
    display: inline-block;
    margin-left: 50%;
    transform: translateX(-50%);
  }
}
.model_container{
  .model_wrap{
    position: absolute;
    border-radius:5px ;
    background: #fff;
    left:50%;
    top:50%;
    transform: translate(-50%,-50%);
  }
  position: fixed;
  z-index: 10000;
  left:0;
  top:0;
  transition: opacity 0.3s;
  right: 0;
  bottom: 0;
}
.mast{
  background-color: #000;
  z-index: 9999;
}
.searchbtn{
  background: linear-gradient(135deg, #fc4838 0%, #f6346b  100%);
  color: #fff;
  min-width: 96px;
  height :36px;
  border :none;
  border-radius: 18px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  margin-left: 20px !important;
}
.searchbtn:focus{
  background: $bg-linear-gradien-red-dark;
  color: #fff;
  min-width: 96px;
  height: 36px;
  border: none;
  border-radius: 18px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  margin-left: 20px !important;
  box-shadow: 0 2px 7px 0 #FAA79B;
}
.searchbtn:hover{
  background :$bg-linear-gradien-red-light;
  color :#fff;
  min-width: 96px;
  height :36px;
  margin-left: 20px !important;
  border: none;
  border-radius: 18px;
  font-size :14px;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 2px 7px 0 #FAA79B;
}
.searchbtn:disabled{
  background: #c0c6c6;
  color :#fff;
  min-width: 96px;
  height :36px;
  font-size :14px;
  font-weight: 500;
  border: none;
  border-radius: 18px;
  cursor: not-allowed;
}
.concellbtn{
  background :#fff;
  color :#303133;
  width: 96px;
  height: 36px;
  font-size: 14px;
  font-weight: 500;
  border :1px solid #E4E7ED;
  border-radius: 18px;
  cursor: pointer;
  // margin-right: 10px;
  margin-left: 10px;
}
.concellbtn:hover{
  background :rgba(220, 223, 230, 0.1);
  color: #303133;
  width :96px;
  height: 36px;
  font-size: 14px;
  font-weight: 500;
  border :1px solid #E4E7ED;
  border-radius: 18px;
  cursor: pointer;
  // margin-right: 10px;
  margin-left: 10px;
}
.concellbtn:focus{
  background :rgba(220, 223, 230, 0.24);
  color: #303133;
  width :96px;
  height: 36px;
  font-size: 14px;
  font-weight: 500;
  border: 1px solid #C0C4CC;
  border-radius: 18px;
  cursor: pointer;
  margin-right: 10px;
  margin-left: 10px;
}
登录后复制

四、调用例子

import React, {useState, useMemo} from &#39;react&#39;
import Modal from &#39;./customPopup/Modal&#39;
/* 挂载方式调用modal */
export default function App() {
    const [ visible , setVisible ] = useState(false)
    const [ nameShow , setNameShow ] = useState(false)
    const handleClick = () => {
        setVisible(!visible)
        setNameShow(!nameShow)
    }
    /* 防止 Model 的 PureComponent 失去作用 */
    const [ handleClose ,handleOk, handleCancel ] = useMemo(()=>{
        const Ok = () =>  console.log(&#39;点击确定按钮&#39;)
        const Close = () => setVisible(false)
        const Cancel = () => console.log(&#39;点击取消按钮&#39;)
        return [Close , Ok , Cancel]
    },[])
    return <div>
        <Modal
            onCancel={handleCancel}
            onClose={handleClose}
            onOk={handleOk}
            title={&#39;标题&#39;}
            visible={visible}
            width={700}
        >
            <div className="feel" >
              内容。。。。。。。
            </div>
        </Modal>
        <button onClick={() => {
            setVisible(!visible)
            setNameShow(false)
        }}
        > model show </button>
        <button onClick={handleClick} > model show ( 显示作者 ) </button>
    </div>
}
登录后复制

实现效果

32f3c5377f5131fd249f58829f49879.jpg

推荐学习:《react视频教程

以上是react怎么实现弹出模态框的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何利用React和WebSocket构建实时聊天应用 如何利用React和WebSocket构建实时聊天应用 Sep 26, 2023 pm 07:46 PM

如何利用React和WebSocket构建实时聊天应用引言:随着互联网的快速发展,实时通讯越来越受到人们的关注。实时聊天应用已经成为现代社交和工作生活中不可或缺的一部分。本文将介绍如何利用React和WebSocket构建一个简单的实时聊天应用,并提供具体的代码示例。一、技术准备在开始构建实时聊天应用之前,我们需要准备以下技术和工具:React:一个用于构建

React前后端分离指南:如何实现前后端的解耦和独立部署 React前后端分离指南:如何实现前后端的解耦和独立部署 Sep 28, 2023 am 10:48 AM

React前后端分离指南:如何实现前后端的解耦和独立部署,需要具体代码示例在当今的Web开发环境中,前后端分离已经成为一种趋势。通过将前端和后端代码分开,可以使得开发工作更加灵活、高效,并且方便进行团队协作。本文将介绍如何使用React实现前后端分离,从而实现解耦和独立部署的目标。首先,我们需要理解什么是前后端分离。传统的Web开发模式中,前端和后端是耦合在

如何利用React和Flask构建简单易用的网络应用 如何利用React和Flask构建简单易用的网络应用 Sep 27, 2023 am 11:09 AM

如何利用React和Flask构建简单易用的网络应用引言:随着互联网的发展,网络应用的需求也越来越多样化和复杂化。为了满足用户对于易用性和性能的要求,使用现代化的技术栈来构建网络应用变得越来越重要。React和Flask是两种在前端和后端开发中非常受欢迎的框架,它们可以很好的结合在一起,用来构建简单易用的网络应用。本文将详细介绍如何利用React和Flask

React响应式设计指南:如何实现自适应的前端布局效果 React响应式设计指南:如何实现自适应的前端布局效果 Sep 26, 2023 am 11:34 AM

React响应式设计指南:如何实现自适应的前端布局效果随着移动设备的普及和用户对多屏幕体验的需求增加,响应式设计成为了现代前端开发的重要考量之一。而React作为目前最流行的前端框架之一,提供了丰富的工具和组件,能够帮助开发人员实现自适应的布局效果。本文将分享一些关于使用React实现响应式设计的指南和技巧,并提供具体的代码示例供参考。使用React的Fle

如何利用React和RabbitMQ构建可靠的消息传递应用 如何利用React和RabbitMQ构建可靠的消息传递应用 Sep 28, 2023 pm 08:24 PM

如何利用React和RabbitMQ构建可靠的消息传递应用引言:现代化的应用程序需要支持可靠的消息传递,以实现实时更新和数据同步等功能。React是一种流行的JavaScript库,用于构建用户界面,而RabbitMQ是一种可靠的消息传递中间件。本文将介绍如何结合React和RabbitMQ构建可靠的消息传递应用,并提供具体的代码示例。RabbitMQ概述:

React代码调试指南:如何快速定位和解决前端bug React代码调试指南:如何快速定位和解决前端bug Sep 26, 2023 pm 02:25 PM

React代码调试指南:如何快速定位和解决前端bug引言:在开发React应用程序时,经常会遇到各种各样的bug,这些bug可能使应用程序崩溃或导致不正确的行为。因此,掌握调试技巧是每个React开发者必备的能力。本文将介绍一些定位和解决前端bug的实用技巧,并提供具体的代码示例,帮助读者快速定位和解决React应用程序中的bug。一、调试工具的选择:在Re

React Router使用指南:如何实现前端路由控制 React Router使用指南:如何实现前端路由控制 Sep 29, 2023 pm 05:45 PM

ReactRouter使用指南:如何实现前端路由控制随着单页应用的流行,前端路由成为了一个不可忽视的重要部分。ReactRouter作为React生态系统中最受欢迎的路由库,提供了丰富的功能和易用的API,使得前端路由的实现变得非常简单和灵活。本文将介绍ReactRouter的使用方法,并提供一些具体的代码示例。安装ReactRouter首先,我们需

如何利用React和Google BigQuery构建快速的数据分析应用 如何利用React和Google BigQuery构建快速的数据分析应用 Sep 26, 2023 pm 06:12 PM

如何利用React和GoogleBigQuery构建快速的数据分析应用引言:在当今信息爆炸的时代,数据分析已经成为了各个行业中不可或缺的环节。而其中,构建快速、高效的数据分析应用则成为了许多企业和个人追求的目标。本文将介绍如何利用React和GoogleBigQuery结合起来构建快速的数据分析应用,并提供详细的代码示例。一、概述React是一个用于构建

See all articles