Files
aurora-admin/frameworks/Popconfirm.jsx
T

83 lines
2.8 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useRef, useState, useEffect } from 'react';
import './Popconfirm.css';
/**
* Aurora Admin Popconfirm(React)
* 对齐 组件2.txt Popconfirm 规范:气泡确认、图标+描述+确认/取消,点击外部关闭
*
* props:
* - title : 确认描述文本
* - okText / cancelText
* - placement : 'bottom' | 'top'
* - visible / defaultVisible : 受控打开
* - onConfirm() / onCancel()
* - children : 触发元素(如按钮)
*/
export default function Popconfirm({
title,
okText = '确定',
cancelText = '取消',
placement = 'bottom',
visible,
defaultVisible = false,
onConfirm,
onCancel,
children
}) {
const rootRef = useRef(null);
const [innerOpen, setInnerOpen] = useState(defaultVisible);
const open = visible !== undefined ? visible : innerOpen;
const [style, setStyle] = useState({});
const syncPos = () => {
if (!rootRef.current) return;
const r = rootRef.current.getBoundingClientRect();
setStyle(placement === 'top'
? { left: r.left, bottom: window.innerHeight - r.top }
: { left: r.left, top: r.bottom + 8 });
};
const setOpen = (v) => {
if (visible === undefined) setInnerOpen(v);
if (v) { syncPos(); document.addEventListener('click', onDocClick, true); window.addEventListener('resize', syncPos); }
else { document.removeEventListener('click', onDocClick, true); window.removeEventListener('resize', syncPos); }
};
const onDocClick = (e) => {
if (rootRef.current && rootRef.current.contains(e.target)) return;
setOpen(false);
};
useEffect(() => {
if (open) { syncPos(); document.addEventListener('click', onDocClick, true); window.addEventListener('resize', syncPos); }
return () => { document.removeEventListener('click', onDocClick, true); window.removeEventListener('resize', syncPos); };
}, [open]);
const confirm = () => { onConfirm && onConfirm(); setOpen(false); };
const cancel = () => { onCancel && onCancel(); setOpen(false); };
return (
<span className="aa-popconfirm" ref={rootRef}>
<span onClick={() => setOpen(!open)}>{children}</span>
{open && (
<div className={`aa-popconfirm-pop placement-${placement}`} style={style}>
<div className="aa-popconfirm-inner">
<span className="aa-popconfirm-icon">!</span>
<span className="aa-popconfirm-title">{title}</span>
</div>
<div className="aa-popconfirm-actions">
<button className="aa-popconfirm-btn" onClick={cancel}>{cancelText}</button>
<button className="aa-popconfirm-btn primary" onClick={confirm}>{okText}</button>
</div>
</div>
)}
</span>
);
}
/*
用法示例:
import Popconfirm from './Popconfirm';
<Popconfirm title="确定要删除吗?" onConfirm={handleDelete}>
<button>删除</button>
</Popconfirm>
*/