React a key copy

  If that, how we achieve React or other framework a key copy of it, in fact, achieved a key code has nothing to do with the frame copy, because he is a native API, we use the following React to achieve it

     effect:

  

 

 

 

  Core code:

    Directly to the red box changed the class name you want to copy elements. (Note that when retrieving an element what I use querySelector)

    The event bound to the elements, you can. The complete code in the bottom

  

  Complete code:

    Note: Icon and message are those derived from antd component library, should not installed antd, other elements can be changed

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(); 将所有选区都清除(即被按住鼠标划中选择的部分)

 

 

通过以上的步骤,一键复制就做好啦!!

Guess you like

Origin www.cnblogs.com/suihang/p/12071117.html