搜索
首页web前端前端问答react 怎么实现拷贝功能

react 怎么实现拷贝功能

Dec 30, 2022 am 11:27 AM
react拷贝

react实现拷贝功能的方法:1、通过“copy-to-clipboard”库实现复制功能;2、使用“react-copy-to-clipboard”库实现复制功能;3、通过“navigator.clipboard.writeText(e)”方法实现复制;4、通过“document.execcommand(“copy”)”方法实现复制;5、通过“copy-js”库实现拷贝功能。

react 怎么实现拷贝功能

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

react 怎么实现拷贝功能?

React中实现一键复制——五种办法

  • copy-to-clipboard库(推荐)
  • react-copy-to-clipboard库(推荐)
  • navigator.clipboard.writeText(e)(推荐)
  • document.execcommand(“copy”)
  • copy-js库

copy-to-clipboard

1、安装方式

// npm安装---这种方式可能会对babel的版本有限制
npm i --save copy-to-clipboard


//cdn引入
<script src="https://wzrd.in/standalone/copy-to-clipboard@latest" async></script>

2、使用方式

import copy from 'copy-to-clipboard';const handleClick = ()=>{
	copy('复制的内容');
	message.success('复制成功')}0ac49d3b14c40e8d204137d7fbf76f9d复制a1cb88e6789f399807801ea3799938af

react-copy-to-clipboard

该方法是基于copy-to-clipboard的,如果在安装copy-to-clipboard的时候,发现和其他部分npm包有版本限制的话,那估计这个也不行,但是也不是不可以试试
1、安装

npm i --save react-copy-to-clipboard

2、用法——这里有个地方要注意,在d2e6d4ef1056974ae0f1f1d2d4feed0954eaac8efc3be0e4829f8d3d1d1d0127中,只能有一个根元素,并且本人亲试,如果在d2e6d4ef1056974ae0f1f1d2d4feed0954eaac8efc3be0e4829f8d3d1d1d0127中,一个根元素裹着两个兄弟节点比如div和一个button的话,复制也不会生效,我也不知道为啥,有兴趣的小伙伴可以去看看源码。

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

 43bbcd4e844b20bc078f8c9897b39d8a {
     if (result) {
       message.success('复制成功');
     } else {
       message.error('复制失败,请稍后再试');
     }
   }}
 >
   a8a83f830be7ccf2b2ad5e838aba8303}
   />
 54eaac8efc3be0e4829f8d3d1d1d0127

document.execcommand(“copy”)——已被弃用

不过好似有的浏览器还可以使用,具体看文档点我
这个方法我没有使用过,有什么坑我也不清楚。

使用方法

42b48c43c2d811927b81b54d0c1f3424一键复制65281c5ac262bf6d81768915a4a77ac0const btn = document.querySelector('#btn');
  btn.addEventListener('click', () => {
      const textarea= document.createElement('textarea');
      textarea.setAttribute('readonly', 'readonly');
      textarea.value = 'xxxxx';
      document.body.appendChild(textarea);
      textarea.select();
      if (document.execCommand('copy')) {
          document.execCommand('copy');
          alert('复制成功');
      }
      document.body.removeChild(textarea);
  })

copy-js库

这块我只是找到了这个库,也没有使用过,但是我看源码底层也是使用的document.execcommand("copy")
1、安装

// npm包下载npm install copy-js --save// CDN导入adf581fd640ebe59dee87c508e6d19bb2cacc6d41bbb37262a98f745aa00fbf0

2、使用

import copy from 'copy-to-clipboard';copy('hello world', function(err) {
    if (err) console.log('Some thing went wrong!');
 
    console.log('Copied!');});

navigator.clipboard.writeText(e)

这个方法也有踩坑的地方,开发时间比较短,也没有具体去研究原因
这个方法的参数e,是需要拿到input文本框的value值为复制的节点

但是这个方法可能在一些应用里边的端内浏览器会有限制,在正常浏览器里是可以使用的,但是比如说现在在飞书端内浏览器里边是没有clipboard这个对象的。还是得看场景使用。

1、使用方法

const { Search } = Input;const copyLink = (e: any) => {
  navigator.clipboard.writeText(e).then(
    () => {
      message.success(intl.t('复制成功'));
      console.log(e);
    },
    () => {
      message.error(intl.t('复制失败,请稍后再试'));
    },
  );};


 462d3c01430fac045c2ece97525bf109

可能还有其他一些方法,暂时没有想到的

推荐学习:《react视频教程

以上是react 怎么实现拷贝功能的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
反应的局限性是什么?反应的局限性是什么?May 02, 2025 am 12:26 AM

Include:1)AsteeplearningCurvedUetoItsVasteCosystem,2)SeochallengesWithClient-SiderEndering,3)潜在的PersperformanceissuesInsuesInlArgeApplications,4)ComplexStateStateManagementAsappsgrow和5)TheneedtokeEedtokeEedtokeEppwithitsrapideDrapidevoltolution.thereedtokeEppectortorservolution.thereedthersrapidevolution.ththesefactorsshesssheou

React的学习曲线:新开发人员的挑战React的学习曲线:新开发人员的挑战May 02, 2025 am 12:24 AM

reactischallengingforbeginnersduetoitssteplearningcurveandparadigmshifttocoment oparchitecent.1)startwithofficialdocumentationforasolidFoundation.2)了解jsxandhowtoembedjavascriptwithinit.3)

为React中的动态列表生成稳定且独特的键为React中的动态列表生成稳定且独特的键May 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript疲劳:与React及其工具保持最新JavaScript疲劳:与React及其工具保持最新May 02, 2025 am 12:19 AM

javascriptfatigueinrectismanagbaiblewithstrategiesLike just just in-timelearninganning and CuratedInformationsources.1)学习whatyouneedwhenyouneedit

使用USESTATE()挂钩的测试组件使用USESTATE()挂钩的测试组件May 02, 2025 am 12:13 AM

totlecteactComponents通过theusestatehook,使用jestandReaCtteTingLibraryToSigulation Interactions andverifyStatAtaTeChangesInTheUI.1)renderthecomponentAndComponentAndComponentAndCheckInitialState.2)模拟useclicklicksorformsormissionsions.3)

React中的钥匙:深入研究性能优化技术React中的钥匙:深入研究性能优化技术May 01, 2025 am 12:25 AM

KeysinreactarecrucialforopTimizingPerformanceByingIneFefitedListupDates.1)useKeyStoIndentifyAndTrackListelements.2)避免使用ArrayIndi​​cesasKeystopreventperformansissues.3)ChooSestableIdentifierslikeIdentifierSlikeItem.idtomaintainAinainCommaintOnconMaintOmentStateAteanDimpperperFermerfermperfermerformperfermerformfermerformfermerformfermerment.ChosestopReventPerformissues.3)

反应中的键是什么?反应中的键是什么?May 01, 2025 am 12:25 AM

ReactKeySareUniqueIdentifiers usedwhenrenderingListstoimprovereConciliation效率。1)heelPreactrackChangesInListItems,2)使用StableanDuniqueIdentifiersLikeItifiersLikeItemidSisRecumended,3)避免使用ArrayIndi​​cesaskeyindicesaskeystopreventopReventOpReventSissUseSuseSuseWithReRefers和4)

反应中独特键的重要性:避免常见的陷阱反应中独特键的重要性:避免常见的陷阱May 01, 2025 am 12:19 AM

独特的keysarecrucialinreactforoptimizingRendering和MaintainingComponentStateTegrity.1)useanaturalAlaluniqueIdentifierFromyourDataiFabable.2)ifnonaturalalientedifierexistsistsists,generateauniqueKeyniqueKeyKeyLiquekeyperaliqeyAliqueLiqueAlighatiSaliqueLiberaryLlikikeuuId.3)deversearrayIndi​​ceSaskeyseSecialIndiceSeasseAsialIndiceAseAsialIndiceAsiall

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器