[英]Copy text from a div to clipboard using document.execCommand in React
在 URL 縮短后,我試圖從div
復制文本。
我在div
中放置了一個ref
值,它將呈現縮短的 URL。 但是,我收到錯誤:
類型錯誤:inputArea.input.select() 不是 function。
我不確定如何引用 div 中的文本。
import { useCallback, useEffect, useRef, useState } from "react";
const Shorten = () => {
const [copySuccess, setCopySuccess] = useState('');
const inputArea = useRef(null);
function copyLink(e){
inputArea.current.select();
document.execCommand('copy');
e.target.focus();
setCopySuccess('Copied!');
};
{isPending && <div className="loading-text">Loading...</div>}
{shortLink && <div ref={inputArea} className="shorten-text">{shortLink}</div>}
<hr></hr>
<div>
<button className="shorten-it" onClick={copyLink} >Copy</button>
{copySuccess}
</div>
</section>
Document.execCommand
將被棄用,取而代之的是現代 剪貼板 API與剪貼板交互。
以下是如何使用剪貼板API:
function updateClipboard(newClip) {
navigator.clipboard.writeText(newClip).then(
() => {
setCopySuccess("Copied!");
},
() => {
setCopySuccess("Copy failed!");
}
);
}
function copyLink() {
navigator.permissions
.query({ name: "clipboard-write" })
.then((result) => {
if (result.state === "granted" || result.state === "prompt") {
updateClipboard(inputArea.current?.innerText);
}
});
}
關於使用剪貼板 API 的注意事項:
剪貼板 API 增加了更大的靈活性,因為您不限於將當前選擇復制到剪貼板,而是可以直接指定要放入剪貼板的信息。
使用 API 要求您在 manifest.json 文件中具有“clipboardRead”或“clipboardWrite”權限。
當頁面處於活動選項卡中時,剪貼板寫入權限會自動授予頁面。 必須請求剪貼板讀取權限,您可以通過嘗試從剪貼板讀取數據來做到這一點。
或者,要使用Document.execCommand
,您應該將div
轉換為input
或textarea
(可以選擇)並使用 CSS 使其看起來像一個 div:
function copyLink(e) {
inputArea.current?.select();
document.execCommand("copy");
e.target.focus();
setCopySuccess("Copied!");
}
// ...
{shortLink && (
<input
ref={inputArea}
type="text"
className="shorten-text"
value={shortLink}
/>
)}
或者,如果您仍想使用div
,請參閱如何將文本從 div 復制到剪貼板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.