React 复制原生写法以及插件使用

// 原生写法(最新写法)
const copyToClipboard = text => {
  // 如果浏览器支持 Clipboard API,则使用它
  if (navigator.clipboard) {
      navigator.clipboard
          .writeText(text)
          .then(function () {
              // console.log('Text successfully copied to clipboard');
          })
          .catch(function (err) {
              console.error('Unable to copy text to clipboard', err);
          });
  } else {
      // 在不支持 Clipboard API 的情况下,使用 document.execCommand 方法
      const textarea = document.createElement('textarea');
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();

      try {
          const successful = document.execCommand('copy');
          const msg = successful ? 'successful' : 'unsuccessful';
          console.log('Text copy was ' + msg);
      } catch (err) {
          console.error('Unable to copy text to clipboard', err);
      }

      document.body.removeChild(textarea);
  }
};

// 使用插件1
npm i copy-to-clipboard --save

import copy from 'copy-to-clipboard';
function coppyUrl(url){
  copy(url);
  alert('复制成功');
};
function App(){
  return <button onClick={()=>coppyUrl('https://www.baidu.com/')}><button>	
};
export default App;


// 使用插件2
npm i react-copy-to-clipboard

import { CopyToClipboard } from 'react-copy-to-clipboard';

<CopyToClipboard 
    text={haggleStore.extension.extensionUrl} 
    onCopy={() => this.handleCopy(haggleStore.extension.extensionUrl)}>
    <span>复制地址</span>
</CopyToClipboard>

// 复制链接
handleCopy = url => {
    if (!url) return false;
    noticeStore.setLastError({ effect: 2, tip: '复制成功' });
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值