搜尋
首頁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('复制成功')}<button>复制</button>

react-copy-to-clipboard

該方法是基於copy-to-clipboard的,如果在安裝copy-to-clipboard的時候,發現和其他部分npm套件有版本限制的話,那估計這個也不行,但是也不是不可以試試
1、安裝

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

2、用法-這裡有個地方要注意,在 <copytoclipboard></copytoclipboard>中,只能有一個根元素,並且本人親試,如果在<copytoclipboard></copytoclipboard>中,一個根元素包裹著一個根元素包裹著兩個兄弟節點例如div和一個button的話,複製也不會生效,我也不知道為啥,有興趣的小夥伴可以去看看源碼。

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

 <copytoclipboard> {
     if (result) {
       message.success('复制成功');
     } else {
       message.error('复制失败,请稍后再试');
     }
   }}
 >
   <button></button>}
   />
 </copytoclipboard>

document.execcommand(“copy”)-已被棄用

不過好似有的瀏覽器還可以使用,具體看文檔點我
這個方法我沒有使用過,有什麼坑我也不清楚。

使用方法

<button>一键复制</button>const 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导入<script></script>

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('复制失败,请稍后再试'));
    },
  );};


 <search></search>

可能還有其他一些方法,暫時沒有想到的

推薦學習:《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

tateractComponents通過theusestatehook,使用jestandReaCtTestingLibraryToSigulationsimintionsandIntractions and verifyStateChangesInTheUI.1)underthecomponentAndComponentAndComponentAndConconentAndCheckInitialState.2)模擬useruseruserusertactionslikeclicksorformsorformsormissions.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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具