import React, { useEffect, useCallback } from 'react';
|
|
/**
|
* 通用弹窗组件
|
*/
|
const ToolModal = ({ visible, title, icon, onClose, children }) => {
|
const handleOverlayClick = useCallback((e) => {
|
if (e.target === e.currentTarget) {
|
onClose();
|
}
|
}, [onClose]);
|
|
// ESC键关闭
|
useEffect(() => {
|
if (!visible) return;
|
|
const handleKeyDown = (e) => {
|
if (e.key === 'Escape') {
|
onClose();
|
}
|
};
|
document.addEventListener('keydown', handleKeyDown);
|
return () => document.removeEventListener('keydown', handleKeyDown);
|
}, [visible, onClose]);
|
|
// 禁止背景滚动
|
useEffect(() => {
|
if (visible) {
|
document.body.style.overflow = 'hidden';
|
} else {
|
document.body.style.overflow = 'auto';
|
}
|
return () => {
|
document.body.style.overflow = 'auto';
|
};
|
}, [visible]);
|
|
// 条件返回放在 Hooks 之后
|
if (!visible) return null;
|
|
return (
|
<div className="modal-overlay active" onClick={handleOverlayClick}>
|
<div className="modal-content">
|
<div className="modal-header">
|
<h2>
|
{icon && <i className={icon}></i>}
|
{title}
|
</h2>
|
<button className="close-btn" onClick={onClose}>
|
×
|
</button>
|
</div>
|
<div className="modal-body">{children}</div>
|
</div>
|
</div>
|
);
|
};
|
|
export default ToolModal;
|