一、需求分析
開發過程中會遇到一鍵復制的需求,解決的方法很簡單,我們只需要在頁面中添加一個 textarea標簽,通過textarea的select方法選中文本,然后再通過瀏覽器提供的copy 命令,將textarea中的內容復制下來即可。
注:瀏覽器提供的copy 命令:document.execCommand("copy")
textarea的select方法:textarea.select()
二、代碼實現
import React from 'react'; import { Button } from 'antd' export default () => { const copyString = () => {
//可以直接復制字符串 // let content = `我尋你千百度 日出到遲暮\r\n一瓢江湖我沉浮\r\n我尋你千百度 又一歲榮枯\r\n可你從不在 燈火闌珊處\r\n` let content = document.getElementById('preId') ?.innerText; if (content) { const el = document.createElement('textarea'); //創建一個textarea el.value = content; //textarea的內容 el.setAttribute('readonly', ''); //添加相應的屬性,不影響整體布局 el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); //textarea添加到body el.select(); //select() 方法只對 <input> 和 <textarea> 有效 document.execCommand('copy'); //拷貝當前選中內容到剪貼板 document.body.removeChild(el); //移除textarea }; } return ( <div> <pre id='preId'>{`我尋你千百度 日出到遲暮 一瓢江湖我沉浮 我尋你千百度 又一歲榮枯 可你從不在 燈火闌珊處 `} </pre> <Button onClick={copyString}>一鍵復制</Button> </div> ); }