import React, { forwardRef, useImperativeHandle, useState, useRef } from 'react'; import './MessagePro.css'; const ICON = { success: '✓', error: '✕', warning: '!', info: 'i', loading: '…' }; const MessagePro = forwardRef(function MessagePro({ duration = 3000 }, ref) { const [list, setList] = useState([]); const idRef = useRef(0); function close(id) { setList(l => l.filter(m => m.id !== id)); } function open(opts) { const id = ++idRef.current; setList(l => [...l, { id, type: opts.type || 'info', content: opts.content, closable: opts.closable }]); const d = opts.duration == null ? duration : opts.duration; if (d > 0) setTimeout(() => close(id), d); return id; } useImperativeHandle(ref, () => ({ open, close, success: (c, d) => open({ type: 'success', content: c, duration: d }), error: (c, d) => open({ type: 'error', content: c, duration: d }), warning: (c, d) => open({ type: 'warning', content: c, duration: d }), info: (c, d) => open({ type: 'info', content: c, duration: d }), loading: (c, d) => open({ type: 'loading', content: c, duration: d }) })); return (
{list.map(m => (
{ICON[m.type] || 'i'} {m.content} {m.closable !== false ? close(m.id)}>✕ : null}
))}
); }); export default MessagePro;