我尝试在 URL 缩短后从 div
复制文本。
我在 div
中放置了一个 ref
值,该值将呈现缩短的 URL。但是,我收到错误:
TypeError: inputArea.input.select() is not a 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
将弃用,取而代之的是现代 Clipboard API与 clipboard 互动.
以下是如何使用剪贴板 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);
}
});
}
使用 Clipboard API 的注意事项:
The Clipboard API adds greater flexibility, in that you aren't limited to copying the current selection into the clipboard, but can directly specify what information to place into the clipboard.
Using the API requires that you have the permission "clipboardRead" or "clipboardWrite" in your manifest.json file.
The clipboard-write permission is granted automatically to pages when they are in the active tab. The clipboard-read permission must be requested, which you can do by trying to read data from the clipboard.
或者,要使用 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}
/>
)}
或者,参见 How to copy text from a div to clipboard如果您仍然想使用 div
。
关于javascript - 在 React 中使用 document.execCommand 将文本从 div 复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67026961/