如何为react-notifications-component原生组件添加剪贴板复制按钮?
实现方案:给react-notifications-component原生通知添加复制按钮
你可以通过封装原生通知结构并注入复制按钮的方式实现,无需完全重写组件,既能保留原生的样式与功能,又能新增复制能力,以下是具体示例:
1. 封装带复制按钮的自定义通知组件
创建复用原生样式的组件,内部包含原生通知的文本区域及新增的复制按钮:
import { useState } from 'react'; const CopyableNotification = ({ title, message, type = 'default', ...rest }) => { const [copied, setCopied] = useState(false); const handleCopy = () => { navigator.clipboard.writeText(message) .then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); }) .catch(err => console.error('复制失败:', err)); }; // 复用库原生类名,保证样式与原生通知一致 return ( <div className={`notification notification-${type}`} style={{ position: 'relative' }}> {title && <div className="notification-title">{title}</div>} <div className="notification-message">{message}</div> <button onClick={handleCopy} style={{ position: 'absolute', top: '8px', right: '40px', border: 'none', background: 'rgba(0,0,0,0.2)', color: '#fff', padding: '4px 8px', borderRadius: '4px', cursor: 'pointer', fontSize: '12px' }} > {copied ? '已复制' : '复制'} </button> </div> ); };
2. 调用封装组件创建通知
使用Store.addNotification时,将content设为该自定义组件,同时传递原生通知所需参数:
import { Store } from 'react-notifications-component'; Store.addNotification({ content: <CopyableNotification title="操作成功" message="这是一条可复制的通知内容" type="success" />, // 保留原生通知的配置项 insert: "top", container: "top-right", animationIn: ["animate__animated", "animate__fadeIn"], animationOut: ["animate__animated", "animate__fadeOut"], dismiss: { duration: 5000, onScreen: true } });
3. 可选:样式适配优化
若原生组件样式存在冲突,可通过自定义CSS调整复制按钮的适配效果:
.notification-copy-btn:hover { background: rgba(0,0,0,0.3); } .notification-success .notification-copy-btn { background: rgba(46, 213, 115, 0.3); } .notification-error .notification-copy-btn { background: rgba(235, 87, 87, 0.3); }
进阶思路:直接复用原生组件
若库版本暴露了原生通知组件(如NotificationItem),可直接组合使用,完全复用原生逻辑:
import { NotificationItem } from 'react-notifications-component'; const CopyableNotificationItem = (props) => { const handleCopy = () => { navigator.clipboard.writeText(props.message); }; return ( <div style={{ position: 'relative' }}> <NotificationItem {...props} /> <button onClick={handleCopy} style={{ position: 'absolute', top: '8px', right: '40px', border: 'none', background: 'rgba(0,0,0,0.2)', color: '#fff', padding: '4px 8px', borderRadius: '4px', cursor: 'pointer', fontSize: '12px' }} >复制</button> </div> ); };
内容的提问来源于stack exchange,提问作者dwurtz
相关产品推荐
相关产品推荐

