1. 程式人生 > 其它 >利用‘clipboard’外掛實現拷貝功能

利用‘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