React一鍵複製
阿新 • • 發佈:2019-12-20
如題,我們怎麼在React或者其他的框架中實現一鍵複製呢,實際上實現一鍵複製的程式碼與框架無關,因為他是用的是原生的API,下面我們用React來實現一下
效果:
核心程式碼:
直接將紅框處改為需要複製的元素類名。(獲取元素時注意一下我用的是querySelector)
將該事件繫結到元素上,即可。完整程式碼在最下方
完整程式碼:
注意:Icon和message均是來自於antd元件庫,如若沒裝antd,改成別的元素即可
import React from 'react'; import './App.css'; import {Icon, message} from 'antd'; class App extends React.Component{ //一鍵複製功能 copy() { const copyEle = document.querySelector('.contentText') // 獲取要複製的節點 const range = document.createRange(); // 創造range window.getSelection().removeAllRanges(); //清除頁面中已有的selection range.selectNode(copyEle); // 選中需要複製的節點 window.getSelection().addRange(range); // 執行選中元素 const copyStatus = document.execCommand("Copy"); // 執行copy操作 // 對成功與否定進行提示 if (copyStatus) { message.success('複製成功'); } else { message.fail('複製失敗'); } window.getSelection().removeAllRanges(); //清除頁面中已有的selection } render() { return ( <div className="App"> <div className="content"> <p className="contentTitle"> <Icon type="copy" onClick={this.copy}/> </p> <p className="contentText"> 我是要被複制的內容啊!!! </p> </div> </div> ); } } export default App;
原理:
我們來看一下具體的步驟:(具體API使用可以查閱MDN)
1. document.querySelector('.contentText') 獲取需要複製的節點
2. document.createRange(); 創造一個區域
3. window.getSelection().removeAllRanges(); 將所有選區都清除(即被按住滑鼠劃中選擇的部分)
4. range.selectNode(copyEle); 選中區域要包含的物件
5. document.execCommand("Copy"); execCommand方法允許執行命令來操縱可編輯內容區域的元素。
6.判斷成功與否
7.window.getSelection().removeAllRanges(); 將所有選區都清除(即被按住滑鼠劃中選擇的部分)
通過以上的步驟,一鍵複製就做好啦!