hooks封装ConfirmModel弹框
1、components/ConfirmModel/index.tsx
import React, { useState, useImperativeHandle } from 'react' import { Modal } from 'antd' import styles from './index.less' import { ExclamationCircleFilled } from '@ant-design/icons' interface DeleteModelProps { childRef?: any handleOk?: (value: any) => void handleCancel?: (value: any) => void text?: string okText?: String cancelText?: String maskClosable?: Boolean className?: String width?: Number isAlignment?: Boolean } const DeleteModel: React.FC<DeleteModelProps> = (props: any) => { const { handleOk, childRef, text, okText, cancelText, maskClosable, className, width, isAlignment } = props const [isModalVisible, setIsModalVisible] = useState(false) const [id, setId] = useState(-1) const showModal = (id?: number) => { setId(id || 0) setIsModalVisible(true) } useImperativeHandle(childRef, () => ({ showModal, handleClose, handleCancel })) const handleClose = () => { setIsModalVisible(false) } const handleCancel = props.handleCancel ? props.handleCancel : handleClose return ( <Modal className={styles.deleteModel + ' ' + `${className}`} visible={isModalVisible} onOk={() => handleOk(id)} onCancel={handleCancel} centered closable={false} width={width ? width : 360} okText={okText || '确认'} cancelText={cancelText || '取消'} maskClosable={maskClosable} // 默认点击蒙层可以关闭,传maskClosable={false}时点击蒙层不可关闭 > <h2> <ExclamationCircleFilled /> <span>提示</span> </h2> <div className={[styles.modelMain, isAlignment ? styles.alignment : ''].join(' ')}>{text ? text : '是否确认删除该条数据,此操作不可恢复!'}</div> </Modal> ) } export default DeleteModel
index.less
:global { .ant-modal-mask, .ant-modal-wrap { z-index: 1030 !important; // 保证【删除确认弹框】在Popover弹层之上 } } .deleteModel { h2 { display: flex; align-items: center; justify-content: center; margin-bottom: 40px; :global(.anticon) { margin-right: 10px; color: #416eff; } > span { color: var(--theme-text-color); font-size: 24px; } } .modelMain { margin-bottom: 0; color: var(--theme-text-color); font-size: 16px; line-height: 24px; text-align: center; } .alignment { display: flex; justify-items: center; text-align: start; } :global { // .ant-modal { .ant-modal-content { padding: 30px 0; .ant-modal-body { padding: 0 20px; } .ant-modal-footer { margin-top: 40px; padding: 0; text-align: center; border-top: 0; .ant-btn { width: 92px; height: 32px; color: #373a44; color: rgba(55, 58, 68, 0.5); font-size: 16px; line-height: 1; border: 1px solid #dde6f7; border-radius: 4px; box-shadow: none; } .ant-btn-primary { margin-left: 50px; color: rgba(255, 255, 255, 1); } } } } // } }
2、使用
import ConfirmModel from '@/components/ConfirmModel'
const deleteRef = useRef<any>() const handleDelete = () => { deleteRef.current.showModal(5) } const handleDeleteOk = async (id: number) => { console.log(id) deleteRef.current.handleCancel() }
DOM:
<div className="iconfont icon-a-shanchu1" onClick={handleDelete}> 删除 </div> <ConfirmModel childRef={deleteRef} handleOk={handleDeleteOk} />
3、效果