react怎麼實作彈出模態框
react實作彈出模態框的方法:1、用createPortal把元素直接渲染到「document.body」下;2、透過「modelShow」和「modelShowAync」來控制彈窗的顯示隱藏;3 、用一個控制器controlShow來流暢執行更新任務即可。
本教學操作環境: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 ? 'block' : 'none'}}> <div className="model_container" style={{opacity: modelShowAsync ? 1 : 0}}> <div className="model_wrap"> <div style={{width: width + 'px'}}> {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 'react' import ReactDOM from 'react-dom' import './style.scss' 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 || '确定'} </button> <button className="concellbtn" onClick={(e) => { onCancel && onCancel(e) }}>{cancelText || '取消'} </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('$$_model_Container_hidden') // 静态属性show——控制 Modal.show = (config) => { // 如果modal已经存在,name就不需要第二次show if (ModalContainer) return const props = {...config, visible: true} const container = ModalContainer = document.createElement('div') // 创建一个管理者,管理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 'react' import Modal from './customPopup/Modal' /* 挂载方式调用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('点击确定按钮') const Close = () => setVisible(false) const Cancel = () => console.log('点击取消按钮') return [Close , Ok , Cancel] },[]) return <div> <Modal onCancel={handleCancel} onClose={handleClose} onOk={handleOk} title={'标题'} 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> }
實作效果
推薦學習:《react影片教學》
以上是react怎麼實作彈出模態框的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

如何利用React和WebSocket建立即時聊天應用程式引言:隨著網路的快速發展,即時通訊越來越受到人們的關注。即時聊天應用程式已成為現代社交和工作生活中不可或缺的一部分。本文將介紹如何利用React和WebSocket建立一個簡單的即時聊天應用,並提供具體的程式碼範例。一、技術準備在開始建立即時聊天應用之前,我們需要準備以下技術和工具:React:一個用於構建

React前後端分離指南:如何實現前後端的解耦和獨立部署,需要具體程式碼範例在當今的Web開發環境中,前後端分離已經成為一種趨勢。透過將前端和後端程式碼分開,可以讓開發工作更加靈活、高效,並且方便進行團隊協作。本文將介紹如何使用React實現前後端分離,從而實現解耦和獨立部署的目標。首先,我們要先理解什麼是前後端分離。傳統的Web開發模式中,前端和後端是耦合在

如何利用React和Flask建構簡單易用的網路應用引言:隨著網路的發展,網路應用的需求也越來越多樣化和複雜化。為了滿足使用者對於易用性和效能的要求,使用現代化的技術堆疊來建立網路應用變得越來越重要。 React和Flask是兩個在前端和後端開發中非常受歡迎的框架,它們可以很好的結合在一起,用來建立簡單易用的網路應用。本文將詳細介紹如何利用React和Flask

如何利用React和RabbitMQ建立可靠的訊息傳遞應用程式引言:現代化的應用程式需要支援可靠的訊息傳遞,以實現即時更新和資料同步等功能。 React是一種流行的JavaScript庫,用於建立使用者介面,而RabbitMQ是一種可靠的訊息傳遞中間件。本文將介紹如何結合React和RabbitMQ建立可靠的訊息傳遞應用,並提供具體的程式碼範例。 RabbitMQ概述:

React響應式設計指南:如何實現自適應的前端佈局效果隨著行動裝置的普及和使用者對多螢幕體驗的需求增加,響應式設計成為了現代前端開發的重要考量之一。而React作為目前最受歡迎的前端框架之一,提供了豐富的工具和元件,能夠幫助開發人員實現自適應的佈局效果。本文將分享一些關於使用React實現響應式設計的指南和技巧,並提供具體的程式碼範例供參考。使用React的Fle

React程式碼偵錯指南:如何快速定位並解決前端bug引言:在開發React應用程式時,經常會遇到各種各樣的bug,這些bug可能會使應用程式崩潰或導致不正確的行為。因此,掌握調試技巧是每個React開發者必備的能力。本文將介紹一些定位和解決前端bug的實用技巧,並提供具體的程式碼範例,幫助讀者快速定位和解決React應用程式中的bug。一、調試工具的選擇:在Re

ReactRouter使用指南:如何實現前端路由控制隨著單頁應用的流行,前端路由成為了一個不可忽視的重要部分。 ReactRouter作為React生態系統中最受歡迎的路由庫,提供了豐富的功能和易用的API,使得前端路由的實作變得非常簡單和靈活。本文將介紹ReactRouter的使用方法,並提供一些具體的程式碼範例。安裝ReactRouter首先,我們需要

如何利用React和GoogleBigQuery建立快速的資料分析應用引言:在當今資訊爆炸的時代,資料分析已經成為了各產業中不可或缺的環節。而其中,建構快速、有效率的資料分析應用則成為了許多企業和個人追求的目標。本文將介紹如何利用React和GoogleBigQuery結合來建立快速的資料分析應用,並提供詳細的程式碼範例。一、概述React是用來構建
