javascript - 在 React 中使用 document.execCommand 将文本从 div 复制到剪贴板

标签 javascript reactjs use-ref

我尝试在 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 APIclipboard 互动.

以下是如何使用剪贴板 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.

Clipboard API (clipboard-write permission) is currently not supported by Firefox but supported by Chrome / Chromium


或者,要使用 Document.execCommand,您应该将 div 转换为 inputtextarea (可以选择)并使用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/

相关文章:

javascript - 如何在 JavaScript 中捕获右键单击事件?

javascript - babel (nextjs/webpack) 无法编译类

html - 如何使用 Typescript 在 React 中定义 <video> 引用的类型?

javascript - 如何映射从数据库中获取的元素?

javascript - 如何使用 react Hook 将 HTML 复制到剪贴板?

reactjs - 使用 ref react 打开选择文件对话框不起作用?

javascript - 音频文件数组

javascript - 排序函数在放入 for 循环时表现不同

javascript - Angular 2.0 : Migration path from Angular 1. x

在服务器上找不到 CSS 样式表?