利用‘clipboard’插件实现拷贝功能
1.安装
npm install clipboard --save
2.引入
import Clipboard from "clipboard";
3.使用
const [copyInfo, setCopyInfo] = useState(''); // 复制的信息
useEffect(() => { //实例化 ClipboardJS对象; let copyBtn = new ClipboardJS('.copyBtn'); copyBtn.on('success', function (e) { // 复制成功 message.destroy(); message.success('复制成功'); e.clearSelection(); }); copyBtn.on('error', function (e) { //复制失败; message.destroy(); message.info('复制失败'); console.log(e.action); }); }, []); // 复制信息 const handleCopy = value => { setCopyInfo(value); setTimeout(() => { document.getElementById('copyBtn').click(); }, 100); }; <button onClick={() => handleCopy('1234567890')}>复制</button> <div style={{position:'absolute',left:'-1000px}}> <input type="text" id="copyVal" readOnly value={copyInfo} /> <button id='copyBtn' className="copyBtn" data-clipboard-target="#copyVal">复制</button> </div>
参考链接:
https://blog.csdn.net/weixin_45439379/article/details/111942258
https://blog.csdn.net/hry2015/article/details/70941912